Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Virtual function invocation from constructor [duplicate]

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?

like image 643
Mizipzor Avatar asked Jul 01 '26 23:07

Mizipzor


1 Answers

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.

like image 161
mghie Avatar answered Jul 03 '26 14:07

mghie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!