MPenate
MPenate

Reputation: 85

C++ Calling overwritten function in derived from base class

I have 2 classes, A and B and I need an overwritten function in B to be called from A's constructor. Here is what I have already:

class A {
    A(char* str) {
        this->foo();
    }

    virtual void foo(){}
}

class B : public A {
    B(char* str) : A(str) {}

    void foo(){
        //stuff here isn't being called
    }
}

How would I get code to be called in B::foo() from A::A()?

Upvotes: 3

Views: 454

Answers (3)

Christophe
Christophe

Reputation: 73366

I need an overwritten function in B to be called from A's constructor

This design is not possible in C++: the order of construction of a B object is that first the base A sub-object is constructed, then B is constructed on top of it.

The consequence is that, while in A constructor, you are still constructing an A object: any virtual function called at this point will be the one for A. Only when the A construction is finished and the B construction starts, will the virtual functions of B become effective.

For achieveing what you want, you have to use a two step pattern: 1) you construct the object, 2) you initialize it.

Upvotes: 3

Piotr Smaroń
Piotr Smaroń

Reputation: 446

I think you are referring to Calling Virtuals During Initialization Idiom (aka Dynamic Binding During Initialization), so please have a look here, where everything is explained:

  1. https://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Calling_Virtuals_During_Initialization
  2. https://isocpp.org/wiki/faq/strange-inheritance#calling-virtuals-from-ctor-idiom

2nd site has very good explanation, but it's way longer than 1st.

Upvotes: 3

Jim Buck
Jim Buck

Reputation: 20726

In a constructor, the base class' function will get called, not the overridden version. The reason for this is that, using your example, B's initialization is not complete when A's constructor is called, and thus calling B's foo would be done with an incomplete B instance if this were otherwise allowed.

Upvotes: 1

Related Questions