I am frankly copying some sample code from Wikipedia Virtual Function :
#include <iostream> #include <vector> class Animal { public: virtual void eat() const { std::cout << "I eat like a generic Animal." << std::endl; } virtual ~Animal() { } }; class Wolf : public Animal { public: void eat() const { std::cout << "I eat like a wolf!" << std::endl; } }; class Fish : public Animal { public: void eat() const { std::cout << "I eat like a fish!" << std::endl; } };
If you call eat() inside the Animal constructor, it will call the Animal eat() function every time. Even if you create a Wolf or Fish object, since the Animal constructor will be completed before the subclass object is initialized, overriding eat functions will not exist yet.
This is a flaw, because it can cause confusion between what is expected and what is actually happening. If I override eat , then create an object of my subclass, I expect my overridden function to be called, even with the Animal link. I expect this because this happens when a call is made explicitly by code outside the constructor. The behavior inside the constructor is different from the other, which makes me confuse my head.
Bill the lizard
source share