Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling base class virtual method by derived class virtual method

Tags:

c++

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;
}
like image 544
Sanish Gopalakrishnan Avatar asked Oct 04 '11 06:10

Sanish Gopalakrishnan


People also ask

How do you call a virtual function from a derived class?

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function.

Can we call base class function using derived class object?

Using a qualified-id to call a base class' function works irrespectively of what happens to that function in the derived class - it can be hidden, it can be overridden, it can be made private (by using a using-declaration), you're directly accessing the base class' function when using a qualified-id.

Can I call virtual function in the base class?

A virtual function is a member function that you expect to be redefined in derived classes. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the function.

When a virtual function is defined by the derived class it is called?

Answer. (b) When a virtual function is redefined by the derived class, it is called as overriding.


2 Answers

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.

like image 81
sharptooth Avatar answered Sep 23 '22 15:09

sharptooth


You can find lots of real-life examples in MFC. For. e.g

CSomeDialog::OnInitDialog()
{
  CDialogEx::OnInitDialog(); //The base class function is called.
  ----
  ----- 
}
like image 36
Madhu Nair Avatar answered Sep 24 '22 15:09

Madhu Nair