Invoking a virtual method of a base class with a virtual method of a derived class

In C ++ - take the case where a derived class is derived from a base class, and in the base class there is a virtual method that the derived class overrides. Can someone tell me a real life scenario where a version of a virtual function of a derived class might require calling a version of a virtual function of a base class?

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; } 
+4
source share
4 answers

You do this every time you also need the behavior of the base class, but do not want (or cannot) override it.

One common example is serialization:

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

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

+11
source

You can find many real world examples in MFC. For. eg

 CSomeDialog::OnInitDialog() { CDialogEx::OnInitDialog(); //The base class function is called. ---- ----- } 
+3
source

Yes, sometimes this is done in serialization:

 class A{ int x; public: A () : x(0) {} virtual void out( Output* o ) { o->write(x); } virtual void in( Input* i ) { i->read(&x); } } class B : public A{ int y; public: B () : y(0) {} virtual void out( Output* o ) { A::out(o); o->write(y); } virtual void in( Input* i ) { A::in(i); i->read(&y); } } 

This is because you want to read / write data for both the parent class and the derived class.

This is a real example of when a derived class should also call the functionality of the base class, as well as add something else to it.

+3
source

In the implementation of the GoF state template, when the substation has an exit() function, so does superconsciousness too. First you need to run the substation exit exit() , then

0
source

All Articles