I blog about development using .net, C#, SQL, Windows RT, and other Microsoft technologies.
Disclaimer: All posts are provided "AS IS" with no warranties, confering no rights, and expressing only my personal opinion, not Microsoft's.
In C++, if you call a virtual function form a constructor, it won’t be polymorphic, meaning that the following code won’t behave as you may have expected:
This would print:
The explanation lies with the order of initialization; The base class is initialized first, hence the base class’s constructor is called first, and when it calls the virtual function, the members in the derived class are not initialized yet. By enforcing that, C++ prevents you from accessing members in the derived class that are not initialized yet!
If you add a "ref" to each class; the behaviour is as expected (virtual function are then called as expected ;) )