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

CSE 143/AE : 1 August 2000


Dispatching review

Given the following class definitions:

class Plant { public: Plant(int init_a) : a(init_a) {} virtual int leaf(int x) { return x * a; } int stem(int x) { return x * leaf(x); } private: int a; }; class Tree : public Plant { public: Tree(int init_a, int init_b) : Plant(init_a), b(init_b) {} virtual int leaf(int x) { return x * b; } int stem(int x) { return x * leaf(b); } virtual int trunk(int x) { return x * stem(x); } private: int b; }; class Moss : public Plant { public: Moss(int init_b) : Plant(0), b(init_b) {} virtual int leaf(int x) { return x * stem(x) + b; } int stem(int x) { return b; } private: int b; };

Which of the following lines are legal? Which are illegal? Why?

Plant p(3); Tree t(20,50); Moss m(-4); Plant * p_ptr = &t; Plant * q_ptr = &m; Tree * t_ptr = p_ptr; Moss * m_ptr = p_ptr; Tree * u_ptr = &t; p_ptr->trunk(3); u_ptr->trunk(3); p_ptr->stem(4);

Answers: Download sample code...


Last modified: Thu Aug 3 15:51:55 PDT 2000