views:

550

answers:

3

Maybe Im to tired, but this seems to be a vary basic question. Suddenly my inheritance chain stopped working. Writing a small basic test application proved that it was me that was wrong (so I cant 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?

+17  A: 

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.

mghie
Oops, the exact same question, strange that one didnt turn up in my searches. Feel free to close this question if anyone wants to.
mizipzor
+2  A: 

See this link for a detailed explanation (for not calling virtual functions from ctor/dtor).

cheers,
mitch

mitchnull
Just skimmed through the article, although it has very valid points, as pointed out in the linked question, there is nothing "c++ invalid" about calling virtual functions in ctor. You just have to be sure about what you get. Although I admit such practices can generate a fair bit of confusion.
mizipzor
+3  A: 

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.

Mr Fooz
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.
mizipzor