2

Suppose I have a base class A and a derived class B. B's constructor calls the constructor of A, in which I call a function, say func to do some type-dependent thing. I mean, I have a do-nothing func for A and override this method in B.

My problem:
In the very phase of construction of B, that is, in the constructor of A, what is the type of the object? While, I think it's A. But I'm not sure. If it is A, I'm always calling A's func right? Regardless of the type of the object I want to construct.
In VS, in B's constructor, I see the type for "this" is "B". While I step into and in A's constructor, I see type for "this" "A".

dudu
  • 801
  • 1
  • 10
  • 32

2 Answers2

4

This is correct. Superclasses are constructed first. Derived classes get constructed only after the superclasses are constructed. Until your superclass A is constructed, none of its virtual methods are overridden, and calling them will invoke A's virtual method. If they are pure and not defined, this results in undefined behavior.

Sam Varshavchik
  • 114,536
  • 5
  • 94
  • 148
0

Well doesn't really matter, as long as control is in B's constructor, code will execute as per B's visibility, if you called your func in B's constructor the overrided func in B is visible hence B's func gets executed, now in A's constructor A's func is visible, hence A's func will get executed.