C++ virtual function from constructor

c++, class, constructor, oop, virtual

Solution

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.

Problem

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; } ```

Original source

Related problems