Question #224677

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”.


Expert's answer

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();
}


 

 

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS