Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

virtual function call from base class

Say we have:

 Class Base {        virtual void f(){g();};     virtual void g(){//Do some Base related code;} };  Class Derived : public Base {        virtual void f(){Base::f();};     virtual void g(){//Do some Derived related code}; };  int main() {     Base *pBase = new Derived;     pBase->f();     return 0;   }  

Which g() will be called from Base::f()? Base::g() or Derived::g()?

Thanks...

like image 899
Gal Goldman Avatar asked Dec 29 '08 09:12

Gal Goldman


People also ask

How do you call base class virtual method from derived class in C++?

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.

How do you call a derived function from base class?

You could do something like this: class Base { public: Base() {} virtual ~Base() {} virtual void start() { startInternal(); } virtual void stop() { stopInternal(); } void doSomething() { startInternal(); // ... stopInternal(); } private: void startInternal() { // ... }

Is a function which calls base class constructor?

When a base class constructor is executing, the object is a base class object. Any virtual function calls execute the base class virtual functions, not the overriding functions in the (as yet unconstructed) derived class.


2 Answers

The g of the derived class will be called. If you want to call the function in the base, call

Base::g(); 

instead. If you want to call the derived, but still want to have the base version be called, arrange that the derived version of g calls the base version in its first statement:

virtual void g() {     Base::g();     // some work related to derived } 

The fact that a function from the base can call a virtual method and control is transferred into the derived class is used in the template method design pattern. For C++, it's better known as Non-Virtual-Interface. It's widely used also in the C++ standard library (C++ stream buffers for example have functions pub... that call virtual functions that do the real work. For example pubseekoff calls the protected seekoff). I wrote an example of that in this answer: How do you validate an object’s internal state?

like image 54
Johannes Schaub - litb Avatar answered Sep 21 '22 21:09

Johannes Schaub - litb


It is the Derived::g, unless you call g in Base's constructor. Because Base constructor is called before Derived object is constructed, Derived::g can not logically be called cause it might manipulate variables that has not been constructed yet, so Base::g will be called.

like image 22
Syed Lavasani Avatar answered Sep 20 '22 21:09

Syed Lavasani