Virtual function invocation from constructor [duplicate]
Asked Answered
D

2

2

Maybe I am wrong, but this seems to be a very basic question. Suddenly my inheritance chain stopped working. Writing a small basic test application proved that it was me that was wrong (so I can't blame the compiler).

I have a base class, with the default behavior in a virtual function. A child class derives from that and changes the behavior.

#include <iostream>

class Base
{
public:
    Base() { print(); }
    ~Base() {}

protected:
    virtual void print() { std::cout << "base\n"; }
};

class Child : public Base
{
public:
    Child() {}
    ~Child() {}

protected:
    virtual void print() { std::cout << "child\n"; }
};

int main()
{
    Base b;
    Child c;
}

This prints:

base
base

When a Child instance is created, why is Base::print() called? I thought that by using the virtual keyword, the function can be replaced for the derived class.

At what point did I get myself confused?

Dela answered 3/2, 2009 at 13:23 Comment(0)
H
18

You are calling a virtual method in the constructor, which is not going to work, as the child class isn't fully initialized yet.

See also this StackOverflow question.

Humour answered 3/2, 2009 at 13:25 Comment(1)
Oops, the exact same question, strange that one didnt turn up in my searches. Feel free to close this question if anyone wants to.Dela
K
4

Although your current problem is the virtual method call from a constructor that others have mentioned, I noticed that you didn't make the destructors virtual. That's normally a bad thing. In your case, the destructors are nops and there are no members that are objects with destructors,... but if your code changes then it's easy for bad things to happen.

Kulp answered 3/2, 2009 at 14:39 Comment(1)
Yes, I get that problem alot about forgetting to make the destructor virtual. Thanks for the heads-up but Im aware of the potential problems.Dela

© 2022 - 2024 — McMap. All rights reserved.