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; }
Because
baseis constructed first and hasn’t ‘matured’ into aderivedyet. It can’t call methods on an object when it can’t guarantee that the object is already properly initialized.