C++ virtual function from constructor

Giovanni Funchal picture Giovanni Funchal · Jan 30, 2009 · Viewed 37.8k times · Source

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

Sean Bright picture Sean Bright · Jan 30, 2009

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.