Polymorphism is one very important feature of C++ and a pivotal concept from OOP. Yet, we often distract ourself to other more restrictive implementations, when what we really need is a C++ Virtual function.
A nice article from a C++guru, Ovidiu Cucu, illustrated this with a rather classical programming example. (http://www.codeguru.com/cpp/cpp/cpp_mfc/general/article.php/c14535__3/)
Let me just quote his final words in this article as a quick note:
"You can implement run-time type checking by using RTTI or the old MFC-like mechanism, but usually that's not absolutely needed."
One more thing I wish to add here. Look at the example from above article using polymorphism methods below; the 'virtual' keyword preceding the function definition in the derived classes are NOT necessary for late-binding to work. Just put it in base class is enough.
Another note: use of pure virtual function is NOT necessary unless you wish to force the user to re-define this method in the derived classes; if a particular function is declared pure virtual, and yet not implemented in derived class, then the code won't compile. There will be a compiler error. In this case, we achieved something similar to 'interface' in Java, if you are familiar with J2SE.
=============================================
#include
class Animal
{
public:
// pure virtual function
virtual void ISay() = 0;
};
class Dog : public Animal
{
public:
// specific implementation for Dog
virtual void ISay() {std::cout };
class Cat : public Animal
{
public:
// specific implementation for Cat
virtual void ISay() {std::cout };
class CFoo
{
public:
void AnimalSays(Animal*);
};
int main(int argc, char* argv[])
{
Dog rex;
Cat kitty;
CFoo foo;
foo.AnimalSays(&rex);
foo.AnimalSays(&kitty);
return 0;
}
void CFoo::AnimalSays(Animal* pAnimal)
{
pAnimal->ISay();
}
=============================================
This post first appeared on Always Remember, You Are At Most Yourself; And, Yo, please read the originial post: here