We have to implement all pure virtual functions in derived class only if the derived class is going to be instantiated. But if the derived class becomes a base class of another derived class and only exists as a base class of more derived classes, then derived class responsibility to implement all their pure virtual functions.
The “middle” class in the hierarchy is allowed to leave the implementation of some pure virtual functions, just like the base class. If the “middle” class does implement a pure virtual function, then its descendants will inherit that implementation, so they don’t have to re-implement it themselves. Let see an example code to understand the concept.
#include<iostream>
using namespace std;
class ISuperbase
{
public:
//pure virtual functions
virtual void print() = 0;
virtual void display() = 0;
};
//derived from Interface
class Base: public ISuperbase
{
public:
virtual void print()
{
cout << "print function of middle class" << endl;
}
};
//derived from Base
class Derived :public Base
{
virtual void display()
{
cout << "In display function" << endl;
}
};
int main()
{
//derive class object
Derived d;
// virtual function, binded at runtime
d.print();
return 0;
}
Answer:
We have to implement all pure virtual functions in derived class only if the derived class is going to be instantiated. But if the derived class becomes a base class of another derived class and only exists as a base class of more derived classes, then derived class responsibility to implement all their pure virtual functions.
The “middle” class in the hierarchy is allowed to leave the implementation of some pure virtual functions, just like the base class. If the “middle” class does implement a pure virtual function, then its descendants will inherit that implementation, so they don’t have to re-implement it themselves. Let see an example code to understand the concept.
Output:
print function of middle class
need an explanation for this answer? contact us directly to get an explanation for this answer