// inherit17.cpp By: Aiman Hanna - ©1993-2005 Aiman Hanna // This program illustrates more on inheritance and virtual functions // in the inheritance tree. The program deals with the problem introduced // in inherit16.cpp. You should notice the output carefully. #include class A { public: void fun() {cout << "A" << endl;}; }; class B : public A { public: virtual void fun() {cout << "B" << endl;}; // The function is made virtual here }; class C : public B { public: void fun() {cout << "C" << endl;}; }; int main() { B *b1; b1 = new C(); b1 -> fun(); delete b1; A *a1; a1 = new C(); // since the function is not virtual, the pointer is actually // made to A (at least from the compiler point-of-view) a1 -> fun(); // this will call fun() defined in A .. expected!! delete (C*)a1; // now you can NOT just delete a1; since this will // attempt to delete an A object, which is not the case. // Such command will result in nothing but run-time error. return 0; } // Compilation Successful /* Output C A */