Reputation: 1711
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();
}
Upvotes: 0
Views: 135
Reputation: 8709
It will be m_steer from B unless you explicitly call it from A like:
A::getSomeParticularInfo()
Upvotes: 1
Reputation: 754725
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.
Upvotes: 6
Reputation: 63775
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
.
Upvotes: 1
Reputation: 1246
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.
Upvotes: 0