Giovanni Funchal Giovanni Funchal - 2 months ago 12
C++ Question

C++ virtual function from constructor

Why the following example prints "0" and what must change for it to print "1" as I expected ?

#include <iostream>
struct base {
virtual const int value() const {
return 0;
}
base() {
std::cout << value() << std::endl;
}
virtual ~base() {}
};

struct derived : public base {
virtual const int value() const {
return 1;
}
};

int main(void) {
derived example;
}

Answer

Because base is constructed first and hasn't "matured" into a derived yet. It can't call methods on an object when it can't guarantee that the object is already properly initialized.

Comments