Sanish Sanish - 1 year ago 119
C++ Question

Calling base class virtual method by derived class virtual method

In C++ - take a case where derived class deriving from a base class and there is a virtual method in base class which the derived class is overriding. Could someone tell me a real life scenario where the derived class version of the virtual function might require to call the base class version of the virtual function?

Example,

class Base
{
public:
Base() {}
virtual ~Base() {}
virtual void display() { cout << "Base version" << endl; }
};

class Derived : public Base
{
public:
Derived() {}
virtual ~Derived() {}
void display();
};

void Derived::display()
{
Base::display(); // a scenario which would require to call like this?
cout << "Derived version" << endl;
}

Answer Source

You do that every time when you also need base class behavior but don't want (or can't) reimplement it.

One common example is serialization:

void Derived::Serialize( Container& where )
{
    Base::Serialize( where );
    // now serialize Derived fields

}

you don't care how base class is serialized, but you definitely want it to serialize (otherwise you lose some data), so you call the base class method.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download