virtual function call from base class

前端 未结 9 1851
故里飘歌
故里飘歌 2020-12-12 17:12

Say we have:


Class Base
{   
    virtual void f(){g();};
    virtual void g(){//Do some Base related code;}
};

Class Derived : public Base
{   
    virtual         


        
9条回答
  •  余生分开走
    2020-12-12 17:44

    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()

提交回复
热议问题