CS 211:
Introduction to Computer Programming II
Instructor: Brian M. Dennis
Teaching Assistants:
Tom Lechner, Bin Lin, Rachel Goldsborough
http://www.cs.northwestern.edu/~bmd/cs211/

A Previous Edition
#ifndef _CONS_H_
#define _CONS_H_ 1
#include "Point.h"
class Cons {
 public:
  Cons(Point* pi, Cons *tail = 0);
  Cons(int xi, int yi, Cons *tail = 0);
  Cons();
  Point* car();
  Cons* cdr();
   ~Cons();
 private:
  Point* p;
  Cons* tail;
};
#endif

A Slightly New Edition
#ifndef _CONS_H_
#define _CONS_H_ 1
#include "Point.h"
class Cons {
 public:
  Cons(Point pi, Cons *tail = 0);
  Cons(int xi, int yi, Cons *tail = 0);
  Cons();
  Point car();
  Cons* cdr();
   ~Cons();
 private:
  Point p;
  Cons* tail;
};
#endif

A Previous Edition
#include <cstring>
#include "Cons.h"
#include <iostream>
using namespace std;
Cons::Cons(Point* pi, Cons *tail)
{
  p = pi;
}
Cons::Cons(int x, int y, Cons *t)
{
  p = new Point(x, y);
  tail = t;
};

A Slightly New Edition
#include <cstring>
#include "Cons.h"
#include <iostream>
using namespace std;
Cons::Cons(Point pi, Cons *tail)
: p(pi)
{
  t = tail;
}
Cons::Cons(int x, int y, Cons *t)
: tail(t), p(x, y)
{
};

Overloaded Functions
int max(int x, int y) {
return (x <= y) ? y : x;
}
char* max(char* s1, char* s2) {
return (strcmp(s1,s2) < 0) ? s2 : s1;
}
Point max(Point p1, Point p2) {
int d1 = sqrt(p1.x() * p1.x() + p1.y() * p1.y());
int d2 = sqrt(p2.x() * p2.x() + p2.y() * p2.y());
return (d1 <= d2) ? p2 : p1;
}

Overloaded Functions
int max(int x, int y);
float max(int x, int y);
int max(float x, float y);
char* max(char* s1, char* s2);
Point max(Point p1, Point p2);
int main(int argc, char* argv[]) {
float f = max(100, 11);
int i = max(1.1, 3.14159);
max("Panthers", "Patriots");
max(Point(5,5), Point(0,4));
}

Overloaded Functions
void print(ostream& os, char* s);
void print(ostream& os, Point& p);
void print(ostream& os, int i)
int main(int argc, char* argv[]) {
print(cout, "It's Howdy Doody Time");
print(cout, Point(10, 20))
print(cout, 100)
exit(0);
}

Overloaded Functions
void print(ostream& os, Point p) {
os << "[" << p.getX() << ","
<< p.gety() << "]";
}
// What if we're really lazy and want
void print(ostream& os, Point p) {
os << "[" << p.x << "," << p.y << "]"
}

Breaking Abstraction
#ifndef _CONS_H_
#define _CONS_H_ 1
#include "Point.h"
#include <iostream>
using std::ostream;
class Cons {
 public:
  Cons(Point pi, Cons *tail = 0);
  Cons(int xi, int yi, Cons *tail = 0);
  Cons(); Point car(); Cons* cdr(); ~Cons();
friend void print(ostream& os, Point p);
friend class Cons;
 private:
  Point p; Cons* tail;
};
#endif

Breaking Abstraction
// Somewhere inside Cons.cpp
int Cons::peekX() {
  return p.x;
}
int Cons::peekY() {
  return p.y;
}

Instance to Instance Access
void Point::add(Point p) {
p.x = p.x + this->x;
p.y = p.y + this->y;
}

That’s a Wrap
Reading
7.1 – 7.7