[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppPolymorphism
'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:
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.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
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:
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]; }
- include <iostream>
- include <vector>
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.
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 }
- include <boost/shared_ptr.hpp>
Code links
- ::,scope operator
- <<,stream out operator
- #include
- assert
- char
- class
- cout
- endl
- for
- #include
- int
- iostream
- main
- return
- scope operator,::
- std
- stream out operator, <<
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
