// C++ example with virtual and non-virtual functions, // subclasses, and overriding // CSE 333 lecture demo, 3/16. HP #include using namespace std; class Thing { public: Thing(int x) { x_ = x; } virtual void setX(int x) { x_ = x; } virtual int getVal() { return x_; } int getNum() { return x_; } private: int x_; }; class Widget: public Thing { public: Widget(int x, int y): Thing(x) { y_ = y; } virtual void setY(int y) { y_ = y; } virtual int getVal() { return y_; } int getNum() { return y_; } private: int y_; }; int main() { Thing *t1 = new Thing(17); Thing *t2 = new Widget(42, 333); Widget *w = dynamic_cast(t2); int n1 = t1->getVal(); int n2 = t2->getVal(); int n3 = w->getVal(); cout << "t1 val = " << n1 << ", t2 val = " << n2 << ", w val = " << n3 << endl; n1 = t1->getNum(); n2 = t2->getNum(); n3 = w->getNum(); cout << "t1 num = " << n1 << ", t2 num = " << n2 << ", w num = " << n3 << endl; return 0; }