Sample - Virtual Functions in C++: Notes Code
#include "iostream.h" //for cout class CBase { public: virtual void PrintVirtual() { cout << "PrintVirtual(): Printing from the base class ..." << endl; } void Print() { cout << "Print(): Printing from the base class ..." << endl; } }; class CDerived: public CBase { public: void PrintVirtual() { cout << "PrintVirtual(): Printing from the derived class ..." << endl; } void Print() { cout << "Print(): Printing from the derived class ..." << endl; } }; void main() { /* * We want to use base class implementation of PrintVirtual() function. */ CBase* pBase = new CBase; pBase->PrintVirtual(); delete pBase; /* * Now, we want to use pointer to the same CBase class to print text * using overridden PrintVirtual() function defined in the derived * class. */ CDerived* pDerived = new CDerived; pBase = pDerived; //or in one line CBase* pBase = new CDerived; pBase->PrintVirtual(); delete pDerived; /* * Next lines remind us that the mechanism of overriding is not * exclusively bounded to virtual functions and polimorphism. * Print() in CDerived has the same name as Print() function in * CBase, and overriding works without use of virtual keyword. */ pDerived = new CDerived; pDerived->Print(); /* * However, in this case pBase pointer cannot be used to * access overriden function in the derived class. */ pBase = new CBase; pBase->Print(); pBase = pDerived; pBase->Print(); //same result! }
Console Output:
PrintVirtual(): Printing from the base class ... PrintVirtual(): Printing from the derived class ... Print(): Printing from the derived class ... Print(): Printing from the base class ... Print(): Printing from the base class ...
(c) 2002, Stan Malevanny