In C++ when a virtual function is called from within a constructor it doesn't behave like a virtual function. I think everyone who encountered for the first time was surprised but on second thought it makes sense, if the derived constructor hasn't yet run the object is not yet a derived so how can a derived function be called? The preconditions haven't had the chance to be set up. Example:
class base {
public:
base()
{
std::cout << "foo is " << foo() << std::endl;
}
virtual int foo() { return 42; }
};
class derived : public foo {
int* ptr_;
public:
derived(int i) : ptr_(new int(i*i)) { }
// The following cannot be called before derived::derived due to how C++ behaves,
// if it was possible... Kaboom!
virtual int foo() { return *ptr_; }
};
It's exactly the same for Java and .NET yet they chose to go the other way, was the only reason the principal of least surprise?
Which do you think is the correct choice?