How can I call a parent constructor after processing?

advertisements

I want to do some processing before the parent constructor is called. The following example shows why I want to do this despite the fact that I have made it slightly trivial for the sake of clarity. The real parent constructor is doing some rendering, but lets try and solve this problem first.

Essentially, the problem comes in when an overriden function is called by the parent constructor, but the child's data is not set up yet. How do I fix this?

class BaseClass {

public:
    int myNumber;

    BaseClass(){
        myNumber = 0;
        this->printNumber();
    }

    virtual void printNumber(){
        printf("My number is %d\n", this->myNumber);
    }
}

class ChildClass : BaseClass {

public:
    float childNumber;

    ChildClass(float myNumber) : BaseClass() {
        this->childNumber = myNumber;
    }

    void printNumber(){
        printf("My number is %f\n", this->childNumber);
    }

}



Like others said above, you shouldn't call a virtual member from a constructor. But to address your problem there is an idiom that might help you, it is called base-from-member:

http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Base-from-Member

What it does basically, is take advantage of the fact that base classes are initialized in the order they are declared. You may be able to do what you need to do in a separate base class before your base class is initialized.

class OtherBaseClass {
    int Num;
    OtherBaseclass(float num) : Num(num)
    {
        printf("My number is %d\n", this->Num);
    }
};

class ChildClass : OtherBaseClass, BaseClass {

public:
    float childNumber;

    ChildClass(float myNumber) : OtherBaseClass(myNumber), BaseClass() {
....