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 caseB::B(). This is a recursive process so what you end up with is the constructors forA,BandCexecuting 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 ofgetSomeParticularInfotoA::getSomeParticularInfoB::B()will set the entry ofgetSomeParticularInfotoB::getSomeParticularInfoAt the point
C::C()has run both the constructor forAandBhave run in that order. Hence any calls togetSomeParticularInfowill resolve toB::getSomeParticularInfoNote: 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.