views:

1973

answers:

6

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...

+15  A: 

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?

Johannes Schaub - litb
A: 

I think you trying to invent Template Method Pattern

Lazin
A: 

As you have defined g() to be virtual, the most derived g() will be looked up in the vtable of the class and called regardless of the type your code is currently accessing it.

See the C++ FAQ on virtual functions.

Thorsten79
+1  A: 

Well... I'm not sure this should compile. The following,

Base *pBase = new Derived;

is invalid unless you have:

Class Derived : public Base

Is it want you meant? If this is want you meant,

pBase->f();

Then the call stack would go like this:

Derived::f()
    Base::f()
        Derived::g()
+1  A: 

Actually running your code shows that Derived::g() is called.

KJAWolf
A: 

pBase is a pointer to a base. pBase = new Derived returns a pointer to a Derived - Derived is-a Base.

So pBase = new Derived is valid.

pBase references a Base, so it will look at Derived as if it were a Base.

pBase->f() will call Derive::f();

Then we see in the code that:

Derive::f() --> Base::f() --> g() - but which g??

Well, it calls Derive::g() because that is the g that pBase "points" to.

Answer: Derive::g()

Jacob