dudu dudu - 1 year ago 93
C++ Question

C++: call overrided method in base class's constructor

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

to do some type-dependent thing. I mean, I have a do-nothing
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
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".

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download