/* Mystery.cpp, by M. Hazen after M. Winstanley CSE 374 class inheritance. */ #include using namespace std; class A { public: A() { cout << "construct a()" << endl; } // constructor ~A() { cout << "destruct ~a" << endl; } // destructor void m1() { cout << "m1:a1" << endl; } void m2() { cout << "m2:a2" << endl; } }; // class B inherits from class A class B : public A { public: B() { cout << "construct b()" << endl; } // extends A() ~B() { cout << "destruct ~b" << endl; } void m1() { cout << "b1" << endl; } void m2() { cout << "b2" << endl; } void m3() { cout << "b3" << endl; } }; int main() { cout << "new x" << endl; A* x = new A(); cout << "new y" << endl; B* y = new B(); cout << "new z" << endl; A* z = new B(); // pointer of type A*, class of type B // B* zz = new A(); // will this work? cout << "A's functions" << endl; x->m1(); x->m2(); cout << "B's functions " << endl; y->m2(); y->m3(); cout << "(z) call m2 no virtual" << endl; z->m2(); // z->m3(); // won't work because Z is of type A, which doesn't have m3 cout << "cast a B to an A" << endl; ((B*)z)->m3(); cout << "cast a B to an A" << endl; ((A*)y)->m2(); cout << "delete x" << endl; delete x; cout << "delete y" << endl; delete y; cout << "delete z" << endl; delete z; }