[Home]  [Edit this page]  [Recent Changes]  [Special Pages]  [Help
CppPolymorphism

(C++) Polymorphism

To cite http://en.wikipedia.org/wiki/Polymorphism_(object-oriented_programming) :

'polymorphism is the ability of objects belonging to different types to respond to methods of the same name, each one according to the right type-specific behavior.'

This is achieved using inheritance: the (abstract) base class defines the common interface of all derived classes.

Below is an example:

  1. include <iostream>
  2. include <vector>
struct MyBaseClass { virtual void sayHello() const = 0; }; struct MyHappyClass : public MyBaseClass { void sayHello() const { std::cout << "Hello!!!" << std::endl; } }; struct MySadClass : public MyBaseClass { void sayHello() const { std::cout << "... hello ..." << std::endl; } }; struct MyAngryClass : public MyBaseClass { void sayHello() const { std::cout << "HELLO!!!" << std::endl; } }; int main() { std::vector<MyBaseClass* > myVector(3); myVector[0] = new MyHappyClass; myVector[1] = new MySadClass; myVector[2] = new MyAngryClass; const unsigned int size = myVector.size(); for (unsigned int i=0; i<size; ++i) myVector[i]->sayHello(); //Clean up for (unsigned int i=0; i<size; ++i) delete myVector[i]; }


What happens is that the vector myVector 'sorts out' which derived class is called to say hello.

Note that the example uses dumb pointers. Below is the same main using the smart pointer boost::shared_ptr.

  1. include <boost/shared_ptr.hpp>
int main() { std::vector<boost::shared_ptr<MyBaseClass> > myVector(3); myVector[0].reset(new MyHappyClass); myVector[1].reset(new MySadClass); myVector[2].reset(new MyAngryClass); const unsigned int size = myVector.size(); for (unsigned int i=0; i<size; ++i) myVector[i]->sayHello(); //No more clean up needed }


Code links



last edited (November 16, 2006) by bilderbikkel, Number of views: 2892, Current Rev: 8 (Diff)

[Edit this page]  [Page history]  [What links here]  [Discuss this topic]  [Printer Friendly]  

Members

Username:

Password:


Register
Forgot Password?




Programmers Heaven - for .NET, Java, C/C++ and WEB Developers!
© 1996-2008 Community Networks Ltd. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited. Violators of this policy may be subject to legal action. Please read Terms Of Use and Privacy Statement for more information. Development by Tore Nestenius at .NET Consultant - Synchron Data.