Search Contact information
University of Cambridge Home Department of Engineering
University of Cambridge >  Engineering Department >  computing help >  Languages >  C++ >  C++crash course

virtual.cc

#include <iostream>
using namespace std;

class Point {
public:
  float x;
  float y;
};

class Shape {
public:
  // Try adding "virtual" to the front of the next line. 
  void draw() { cout << "Shape's draw routine\n";} ;
  // Note that replacing the above line by
  // "virtual void draw()=0;" should force derived classes to
  // have draw() routines. See if this is true.
  float area;
};

class Triangle: public Shape {
  Point points[3];
  void draw() { cout << "Triangle's draw routine\n";} ;
};

class Rectangle: public Shape {
  Point points[4];
  void draw() { cout << "Rectangle's draw routine\n";} ;
};


int main() {

Triangle t1, t2;
Rectangle r1, r2;

Shape* shapes[4];
shapes[0]=&t1; 
shapes[1]=&r1; 
shapes[2]=&t2; 
shapes[3]=&r2;

for (int i=0;i<4; i++)
   shapes[i]->draw();
}

[ C++ course Classes page ] [ C++ course contents page ]
© Cambridge University Engineering Dept
Information provided by Tim Love (tpl)
Last updated: October 2001