Justify the following statement with the help of a suitable example: “In a class hierarchy of several levels of several levels, if we want a function at any level to be called through a base class pointer then the function must be declared as virtual in the base class”.
Virtual functions are class members declared in the base or parent class and are redefined or overridden in the derived classes.
#include<iostream>
using namespace std;
class baseClass {
public:
virtual void printing()
{
cout << "This is the base class\n" << endl;
}
void showing()
{
cout << "\nShowing the base class\n" << endl;
}
};
class derivedClass : public baseClass {
public:
void printing()
{
cout << "This is the derived class\n. The printing() function has been overriden class\n" << endl;
}
void showing()
{
cout << "Show the derived class\n.Showing() method has been overriden by calling this method" << endl;
}
};
class derivedDerivedClass : public derivedClass {
public :
void printing()
{
cout << "printing derived_derived class\n.";
}
void showing()
{
cout << "showing derived_derived class\n";
}
};
int main()
{
baseClass* basePtr;
derivedDerivedClass derivedDerivedObj;
basePtr = &derivedDerivedObj;
basePtr->printing();
basePtr->showing();
}
Comments
Leave a comment