Why do constructors ignore overriden virtual functions?

118 Views Asked by At

Heres an example:

struct parent {
    int a;

    virtual void stuff() { a = 5; } //variant A
    void roundabout() { stuff(); }
    parent() { stuff(); }
};

struct child : parent {
    void stuff() override { a = 6; } //variant B
    child() : parent() {}
};

and usage

child c;  //calls variant A
auto p = reinterpret_cast<parent*>(&c);

c.stuff(); //calls variant B
c.roundabout(); //calls variant B
p->stuff(); //calls variant B
p->roundabout() //calls variant B

so after construction, any which way I call stuff() from inside or outside the class, without explicitly stating parent::stuff() I get child::stuff(), as expected.

The one exception is the constructor of parent that still calls parent::stuff() even though its triggered by the child constructor. This is really rather annoying since I have to include extra logic in the functions that the constructors call to make them behave as they should. Why is it like this?

1

There are 1 best solutions below

0
David Schwartz On

An instance of child cannot exist unless an instance of parent already exists. So in the constructor of parent, no instance of child can exist. So how could you call child::stuff if no child exists?