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;
}
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.
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.
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.
Answer. (b) When a virtual function is redefined by the derived class, it is called as overriding.
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.
You can find lots of real-life examples in MFC. For. e.g
CSomeDialog::OnInitDialog()
{
CDialogEx::OnInitDialog(); //The base class function is called.
----
-----
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With