1

I am new to these important features of C++, i have already read a few question/answers on these topics here and googled a few docs. But i am still confused with this...

It would be great if some one can advice me some good online tutorial or book chapter which takes this concepts easy and slow and starts it from the basic.

Also, if some one knows some on-hand exercise material that would be great.

LihO
  • 41,190
  • 11
  • 99
  • 167
mu_sa
  • 2,685
  • 10
  • 39
  • 58
  • Please see [The C++ book list](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – MSalters Feb 13 '12 at 11:54
  • Try to have a look at this book list http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list – Damian Feb 13 '12 at 11:54

1 Answers1

7

Here's the best explanation of polymorphism that I've ever heard:

There are many animals in this world. Most of them make some sound:

class Animal
{
public:
    virtual void throwAgainstWall() { };
};

class Cat : public Animal
{
public:
    void throwAgainstWall(){ cout << "MEOW!" << endl; }
};

class Cow : public Animal
{
public:
    void throwAgainstWall(){ cout << "MOOO!" << endl; }
};

Now imagine you have huge bag with animals and you can't see them. You just grab one of them and throw it against wall. Then you listen to its sound - that tells you what kind of animal it was:

set<Animal*> bagWithAnimals;
bagWithAnimals.insert(new Cat);
bagWithAnimals.insert(new Cow);

Animal* someAnimal = *(bagWithAnimals.begin());
someAnimal->throwAgainstWall();

someAnimal = *(bagWithAnimals.rbegin());
someAnimal->throwAgainstWall();

You grab first animal, throw it against wall, you hear "MEOW!" - Yeah, that was cat. Then you grab the next one, you throw it, you hear "MOOO!" - That was cow. That's polymorphism.

You should also check Polymorphism in c++

And if you are looking for good book, here is good list of 'em: The Definitive C++ Book Guide and List

Community
  • 1
  • 1
LihO
  • 41,190
  • 11
  • 99
  • 167
  • Thanks..You are spot on when you say that there is huge amount of material available on Polymorphism. What i am more precisely looking is too learn it by doing (i.e exercise). – mu_sa Feb 13 '12 at 12:15
  • @MuhammadSalman : Before you start "experimenting" and practicing it, you should understand the basics. – LihO Feb 13 '12 at 12:16
  • The problem with the books is that i dont have much time on my hand(atleast now) and i cannot try different books to see if it is what i am looking for learning polymorpism. I need advice, from people who have read a few books, on which book provides the best and thorough explanation on polymorphism . – mu_sa Feb 13 '12 at 12:24
  • @MuhammadSalman : I would appreciate if you [accept](http://meta.stackoverflow.com/content/img/faq/faq-accept-answer.png) my answer in case it helped you ;) – LihO Feb 15 '12 at 20:10
  • Thanks LihO, indeed its helpful :) – mu_sa Feb 16 '12 at 09:29