[   ^ to index...   |   <-- previous   |   next -->   ]

Inheritance puzzle

Consider the following class heirarchy:

class Whale { public: Whale(int x) { this->x = x; } int squid() { return x; } virtual int clam() { return x; } private: int x; }; class Baleen : public Whale { public: Baleen(int x, int y) : Whale(x) { this->y = y; } int squid() { return y; } virtual int clam() { return y; } private: int y; }; class Humpback : public Baleen { public: Humpback(int x, int y, int z) : Baleen(x, y) { this->z = z; } int squid() { return z; } virtual int clam() { return z; } private: int z; };

What is printed by the following code?

Whale w(5); Whale * wp = new Baleen(2, 3); Baleen * bp = new Humpback(10, 11, 12); Baleen b = *bp; cout << wp->squid() << endl; cout << wp->clam() << endl; cout << bp->squid() << endl; cout << bp->clam() << endl; cout << b.squid() << endl; cout << b.clam() << endl;

Last modified: Mon Jul 24 15:28:22 PDT 2000