Answer to Question #224677 in C++ for Umar

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


1
Expert's answer
2021-08-10T04:28:29-0400

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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS