In addition to other excellent answers, one thing very important, and usually ignored/forgotten, or misunderstood (which explains why I detail the process below):
- In Java, methods are virtual, even when called from the constructor (which could lead to bugs)
- In C++, virtual methods are not virtual when called from the constructor (which could lead to misunderstanding)
What?
- Let's imagine a Base class, with a virtual method foo().
- Let's imagine a Derived class, inheriting from Base, who overrides the method foo()
The difference between C++ and Java is:
- In Java, calling foo() from the Base class constructor will call Derived.foo()
- In C++, calling foo() from the Base class constructor will call Base.foo()
Why?
The "bugs" for each languages are different:
- In Java, calling any method in the constructor could lead to subtle bugs, as the overridden virtual method could try to access a variable which was declared/initialized in the Derived class.
Conceptually, the constructor’s job is to bring the object into existence (which is hardly an ordinary feat). Inside any constructor, the entire object might be only partially formed – you can know only that the base-class objects have been initialized, but you cannot know which classes are inherited from you. A dynamically-bound method call, however, reaches “forward” or “outward” into the inheritance hierarchy. It calls a method in a derived class. If you do this inside a constructor, you call a method that might manipulate members that haven’t been initialized yet – a sure recipe for disaster.
Bruce Eckel, http://www.codeguru.com/java/tij/tij0082.shtml
- In C++, one must remember a virtual won't work as expected, as only the method of the current constructed class will be called. The reason is to avoid accessing data members or even methods that do not exist yet.
During base class construction, virtual functions never go down into derived classes. Instead, the object behaves as if it were of the base type. Informally speaking, during base class construction, virtual functions aren't.
Scott Meyers, http://www.artima.com/cppsource/nevercall.html