简体   繁体   中英

Inheritance and virtual member functions

I am not 100% sure the outcome that would occur in my current setup up.

This maybe a stupid question, but I can not see a similar example.

Here is the example code

Class A {

  public:
    virtual Steer* getSomeParticularInfo(){ return m_steer; }

  private:
    Steer* m_steer:
}


Class B: A {

  public:
    virtual Steer* getSomeParticularInfo(){ return m_steer; }

  private:
    Steer* m_steer:
}

Class C: B {

  public:
    //Does not have its own getSomeParticularInfo() member function

  private:
    Steer* m_steer:
}

My question:

If I call getSomeParticularInfo. Will it come from Class B because it is the most recent derived class or does it come from the base class?

//Inside Class C constructor
C::C(){
  m_steer = getSomeParticularInfo();
}

In order to understand this you need to understand the order of constructors here. Before the body of C::C() is executed the constructor for the base type is executed. In this case B::B() . This is a recursive process so what you end up with is the constructors for A , B and C executing in order.

The constructor of a type in C++ will change the virtual method table to point to the version of a virtual method / override that it defines. Hence

  • A::A() will set the entry of getSomeParticularInfo to A::getSomeParticularInfo
  • B::B() will set the entry of getSomeParticularInfo to B::getSomeParticularInfo

At the point C::C() has run both the constructor for A and B have run in that order. Hence any calls to getSomeParticularInfo will resolve to B::getSomeParticularInfo

Note: In general I would avoid using virtual methods in the constructor. It's generally speaking a bad practice because of the potential for confusion it creates.

It will call B::getSomeParticularInfo()

And that function, as compiled will knowingly ignore A::m_steer and will not be aware of the existence of C::m_steer .

除非您从A显式调用它,否则它将是B的m_steer:

A::getSomeParticularInfo()

Yes. If you call getSomeParticularInfo() from C it will be the m_steer from B.

The only problem with the snippet above is that you shouldn't call virtual methods from constructors.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM