// Here is an object which has two base classes. It is one of the shapes // (a Square), and also a Stack_Elt so it can be put on the stack. class StackedSquare: public Square, public Stack_Elt { public: StackedSquare(int x, int y, int side): Square(x, y, side) { } void print(ostream& strm) const { strm << "Square[" << width << " @ " << origx << "x" << origy << "]"; } };
main() { Canvas c(35, 60); // A place to draw. Stack s; // A stack of squares.
// Draw some squares, then put the on a stack. int size = 22; for(int m = 1; m <= 7; m++) { StackedSquare *ss = new StackedSquare(4*m, m + 1, size); size -= 3; s.push(ss); ss->draw(c); }
// Pop them off, move 'em a bit, then draw them again. int move = 0; while(!s.empty()) { StackedSquare *ss = (StackedSquare *)s.pop(); ss->translate(move, 25 + move); ++move; ss->draw(c); delete ss; }
c.print(cout); }
C++ allows multiple inheritance: A class may have more than one base class. Java does not permit multiple inheritance, but the Java interface system is actually a limited form of this. Java seems to have the right idea here. Interfaces seem to allow the useful applications of multiple inheritance, and forbid the stupid ones.