220 likes | 325 Views
Course Title : OOP Using C++. Chapter No: 04. Chapter No: 04. COURSE INSTRUCTOR : ILTAF MEHDI. Polymorphism. The word polymorphism is a combination of two words poly and Morphism.
E N D
CourseTitle:OOP Using C++ Chapter No: 04 Chapter No: 04 COURSE INSTRUCTOR: ILTAF MEHDI
Polymorphism • The word polymorphism is a combination of two words poly and Morphism. • Poly means many and Morphism means form. In OOP polymorphism is the ability of objects of different types of respond to functions of the same name. the user does not have know the exact type of the object in advance. • The behavior of the object can be implemented at the run time. It is called late binding or dynamic binding. Polymorphism is implemented by using virtual function.
Advantages of POLYMORPHISM • It is one of the outstanding feature of OOP. • In it objects of different classes related by inheritance receive a same message (function call) and respond differently. • One interface & multiple methods. • One thing having different shapes
Pointer to Object • A pointer can also refers to an object of a class. The member of an object can be accessed through pointers by the symbol -> • The saymbol is known as member access operator. • Syntax ; • ptr -> member
Create a prog that show the use of pointer by using polymorphism • #include <iostream.h> • #include <conio.h> • class Test • { • private: int*n; • public: • void in(void); • { cout <<“enter number”; cin>>n; } • void out(void); • { • cout <<“the value of n: “<<n<<endl; • cout <<“address”<<&n<<endl; • } • }; • Void main(void) • { • clrscr(); • Test *ptr; • ptr = new Test; • ptr -> in(); • ptr->out(); • getch(); • }
POLYMORPHISM Pure Virtual Function Class ball:public drawing { public: ---------- void draw() { --------} }; class drawing { public: virtual void draw()=0 { ----------} }; class drawing { public: void draw() { ----------} }; LATE BINDING EARLY BINDING void main() { ball objball;rectobjrect; P=&objball; pdraw(); pdraw(); P=&objrect; pdraw(); pdraw(); } Class rect:public drawing { public: void draw() {--------} };
ABSTRACT CLASS • A class having one or more pure virtual function is called Abstract class. • Object of the abstract class can not be created . CONCRETE CLASS • A class having no pure virtual function is called Concrete class. • Object of the concrete class can be created .
Friendship and inheritance • In principle, private and protected members of a class cannot be accessed from outside the same class in which they are declared. However, this rule does not affect friends. • Friends are functions or classes declared as such. • If we want to declare an external function as friend of a class, thus allowing this function to have access to the private and protected members of this class, we do it by declaring a prototype of this external function within the class, and preceding it with the keyword friend.
Friend functions CRectangle duplicate (CRectanglerectparam) { CRectanglerectres; rectres.width = rectparam.width*2; rectres.height = rectparam.height*2; return (rectres); } int main () { CRectanglerect, rectb; rect.set_values (2,3); rectb = duplicate (rect); cout << rectb.area(); return 0; } #include <iostream> class CRectangle { int width, height; public: void set_values (int, int); int area () {return (width * height);} friend CRectangle duplicate (CRectangle); }; void CRectangle::set_values (int a, int b) { width = a; height = b; }
Friend classes Just as we have the possibility to define a friend function, we can also define a class as friend of another one, granting that first class access to the protected and private members of the second one. void CRectangle::convert (CSquare a) { width = a.side; height = a.side; } int main () { CSquare sqr; Crectangle rect; sqr.set_side(4); rect.convert(sqr); cout << rect.area(); return 0; } • #include <iostream.h> • class CSquare; • class Crectangle • { • int width, height; • public: • int area () • { • return (width * height);} • void convert (CSquare a); }; • class CSquare { • private: • int side; • public: • void set_side (int a) • {side=a;} • friend class CRectangle; • };
Class Interface Diagram Timeclass ExtTimeclass Set Set Protected data: hrs mins secs Increment Increment Write Write ExtTime Time ExtTime Time Private data: zone
Static Binding • When the type of a formal parameter is a parent class, the argument used can be: the same type as the formal parameter, or, any derived class type. • Static binding is the compile-time determination of which function to call for a particular object based on the type of the formal parameter • When pass-by-value is used, static binding occurs
Dynamic Binding • Is the run-time determination of which function to call for a particular object of a derived class based on the type of the argument • Declaring a member function to be virtual instructs the compiler to generate code that guarantees dynamic binding • Dynamic binding requires pass-by-reference
Virtual Member Function // SPECIFICATION FILE ( time.h ) class Time { public : . . . virtual void Write ( ) ; // for dynamic binding virtual ~Time(); // destructor private : int hrs ; int mins ; int secs ; } ;
Time::write() ExtTime::write() This is the way we like to see… void Print (Time * someTime ) { cout << “Time is “ ; someTime->Write ( ) ; cout << endl ; } OUTPUT Time is 08:30:00 Time is 10:45:00 CST CLIENT CODE Time startTime( 8, 30, 0 ) ; ExtTime endTime(10, 45, 0, CST) ; Time *timeptr; timeptr = &startTime; Print ( timeptr ) ; timeptr = &endTime; Print ( timeptr ) ;
Virtual Functions • Virtual Functions overcome the problem of run time object determination • Keyword virtual instructsthe compiler to use late binding and delay the object interpretation • How ? • Define a virtual function in the base class. The word virtual appears only in the base class • If a base class declares a virtual function, it must implement that function, even if the body is empty • Virtual function in base class stays virtual in all the derived classes • It can be overridden in the derived classes • But, a derived class is not required to re-implement a virtual function. If it does not, the base class version is used
Abstract Classes & Pure Virtual Functions • Some classes exist logically but not physically. • Example : Shape • Shape s; // Legal but silly..!! : “Shapeless shape” • Shape makes sense only as a base of some classes derived from it. Serves as a “category” • Hence instantiation of such a class must be prevented class Shape //Abstract {public ://Pure virtual Functionvirtual void draw() = 0; } A class with one or more pure virtual functions is an Abstract Class Objects of abstract class can’t be created Shape s; // error : variable of an abstract class
Example Shape virtual void draw() Circle Triangle public void draw() public void draw()
A pure virtual function not defined in the derived class remains a pure virtual function. • Hence derived class also becomes abstract class Circle : public Shape { //No draw() - Abstractpublic :void print(){cout << “I am a circle” << endl;} class Rectangle : public Shape {public :void draw(){ // Override Shape::draw()cout << “Drawing Rectangle” << endl;} Rectangle r; // Valid Circle c; // error : variable of an abstract class
Polymorphism Summary: • When you use virtual functions, compiler store additional information about the types of object available and created • Polymorphism is supported at this additional overhead • Important : • virtual functions work only with pointers/references • with objects even if the function is virtual • If a class declares any virtual methods, the destructor of the class should be declared as virtual as well.
Pure virtual functions : Summary • Pure virtual functions are useful because they make explicit the abstractness of a class • Tell both the user and the compiler how it was intended to be used • Note : It is a good idea to keep the common code as close as possible to the root of you hierarchy
Summary ..continued • It is still possible to provide definition of a pure virtual function in the base class • The class still remains abstract and functions must be redefined in the derived classes, but a common piece of code can be kept there to facilitate reuse • In this case, they can not be declared inline class Shape { //Abstractpublic :virtual void draw() = 0; };// OK, not defined inlinevoid Shape::draw(){ cout << “Shape" << endl;} class Rectangle : public Shape {public :void draw(){Shape::draw(); //Reusecout <<“Rectangle”<< endl;}