Poly

|
All materials on our website are shared by users. If you have any questions about copyright issues, please report us to resolve them. We are always happy to assist you.
 25 views
of 7

Please download to get full document.

View again

Description
poly
Share
Tags
Transcript
  Polymorphism Before getting into this section, it is recommended that you have a proper understanding of pointers and class inheritance. If any of the following statements seem strange to you, youshould review the indicated sections: Statement: Explained in: int a::b(int c) { } Classesa->b Data Structuresclass a: public b { }; Friendship and inheritance Pointers to base class One of the key features of derived classes is that a pointer to a derived class is type-compatible with a pointer to its base class. Polymorphism is the art of taking advantage of this simple but powerful and versatile feature, that brings Object Oriented Methodologies toits full potential.We are going to start by rewriting our program about the rectangle and the triangle of theprevious section taking into consideration this pointer compatibility property:12345678910111213141516171819202122232425262728 // pointers to base class #include <iostream> using namespacestd; classCPolygon {protected:intwidth, height;public:voidset_values (inta,intb) { width=a; height=b; }};classCRectangle:publicCPolygon { public:intarea (){return(width * height); }};classCTriangle:publicCPolygon { public:intarea (){return(width * height / 2); }};intmain () {CRectangle rect;CTriangle trgl;CPolygon * ppoly1 = &rect;2010  29303132333435CPolygon * ppoly2 = &trgl;ppoly1->set_values (4,5);ppoly2->set_values (4,5);cout << rect.area() << endl;cout << trgl.area() << endl;return0;}In function main, we create two pointers that point to objects of class CPolygon (ppoly1 and ppoly2). Then we assign references to rect and trgl to thesepointers, and because both are objects of classes derived fromCPolygon, both are validassignment operations.The only limitation in using *ppoly1 and *ppoly2 instead of rect and trgl is thatboth *ppoly1 and *ppoly2 are of type CPolygon* and therefore we can only use thesepointers to refer to the members that CRectangle andCTriangle inherit from CPolygon. Forthat reason when we call the area() members at the end of the program we have had to usedirectly the objects rect and trgl instead of the pointers *ppoly1 and *ppoly2.In order to use area() with the pointers to class CPolygon, this member should also have beendeclared in the class CPolygon, and not only in its derived classes, but the problem isthat CRectangle and CTriangle implement different versions of area, therefore we cannotimplement it in the base class. This is when virtual members become handy: Virtual members A member of a class that can be redefined in its derived classes is known as a virtualmember. In order to declare a member of a class as virtual, we must precede its declarationwith the keyword virtual:1234567891011121314151617 // virtual members #include <iostream> using namespacestd; classCPolygon {protected:intwidth, height;public:voidset_values (inta,intb) { width=a; height=b; }virtual intarea () {return(0); }};classCRectangle:publicCPolygon { public:intarea ()20100  181920212223242526272829303132333435363738394041{return(width * height); }};classCTriangle:publicCPolygon { public:intarea (){return(width * height / 2); }};intmain () {CRectangle rect;CTriangle trgl;CPolygon poly;CPolygon * ppoly1 = &rect;CPolygon * ppoly2 = &trgl;CPolygon * ppoly3 = &poly;ppoly1->set_values (4,5);ppoly2->set_values (4,5);ppoly3->set_values (4,5);cout << ppoly1->area() << endl;cout << ppoly2->area() << endl;cout << ppoly3->area() << endl;return0;}Now the three classes (CPolygon, CRectangle and CTriangle) have all the samemembers: width, height,set_values() and area().The member function area() has been declared as virtual in the base class because it is laterredefined in each derived class. You can verify if you want that if you removethis virtual keyword from the declaration of area()within CPolygon, and then you run theprogram the result will be 0 for the three polygons instead of 20, 10 and 0. That is becauseinstead of calling the corresponding area() function for each object(CRectangle::area(),CTriangle::area() and CPolygon::area(),respectively), CPolygon::area() will be called in all cases since the calls are via a pointerwhose type is CPolygon*.Therefore, what the virtual keyword does is to allow a member of a derived class with thesame name as one in the base class to be appropriately called from a pointer, and moreprecisely when the type of the pointer is a pointer to the base class but is pointing to an objectof the derived class, as in the above example.A class that declares or inherits a virtual function is called a  polymorphic class .Note that despite of its virtuality, we have also been able to declare an object of type CPolygon and to call its ownarea() function, which always returns 0.  Abstract base classes Abstract base classes are something very similar to our CPolygon class of our previousexample. The only difference is that in our previous example we have defined avalid area() function with a minimal functionality for objects that were of class CPolygon (like the object poly), whereas in an abstract base classes we could leavethat area()member function without implementation at all. This is done byappending =0 (equal to zero) to the function declaration.An abstract base CPolygon class could look like this:123456789 // abstract class CPolygon classCPolygon {protected:intwidth, height;public:voidset_values (inta,intb) { width=a; height=b; }virtual intarea () =0; };Notice how we appended =0 to virtual int area () instead of specifying an implementation forthe function. This type of function is called a  pure virtual function , and all classes thatcontain at least one pure virtual function are abstract base classes .The main difference between an abstract base class and a regular polymorphic class is thatbecause in abstract base classes at least one of its members lacks implementation we cannotcreate instances (objects) of it.But a class that cannot instantiate objects is not totally useless. We can create pointers to itand take advantage of all its polymorphic abilities. Therefore a declaration like:CPolygon poly;would not be valid for the abstract base class we have just declared, because tries toinstantiate an object. Nevertheless, the following pointers:12CPolygon * ppoly1;CPolygon * ppoly2;would be perfectly valid.This is so for as long as CPolygon includes a pure virtual function and therefore it's anabstract base class. However, pointers to this abstract base class can be used to point toobjects of derived classes.
Related Search
We Need Your Support
Thank you for visiting our website and your interest in our free products and services. We are nonprofit website to share and download documents. To the running of this website, we need your help to support us.

Thanks to everyone for your continued support.

No, Thanks
SAVE OUR EARTH

We need your sign to support Project to invent "SMART AND CONTROLLABLE REFLECTIVE BALLOONS" to cover the Sun and Save Our Earth.

More details...

Sign Now!

We are very appreciated for your Prompt Action!

x