Search code examples
c++functioninheritancepolymorphismvirtual

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()?


Solution

  • 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.