Calling a virtual function from the constructor

Maybe I'm wrong, but this seems to be a very simple question. Suddenly my inheritance network stopped working. Writing a small basic test application showed that it was wrong, so I cannot blame the compiler.

I have a base class with default behavior in a virtual function. The child class follows from this and changes its 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;
}

Fingerprints:

base
base

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

At what point am I embarrassed?

+2
source share
3 answers
+18

- , , , . . nops, , , , .

+4

. ( , ctor/dtor).

+2

All Articles