Chapter 5 Polymorphism

59
1 MTS 3033 - Object Oriented Programming

description

OOP

Transcript of Chapter 5 Polymorphism

Page 1: Chapter 5 Polymorphism

1MTS 3033 - Object Oriented Programming

Page 2: Chapter 5 Polymorphism

The word polymorphism is derived from the Greek words poly and morphism.

Poly refers to many or multiple and morphism refers to actions namely performing many actions with a single operator.

2MTS 3033 - Object Oriented Programming

Page 3: Chapter 5 Polymorphism

Function overloading Polymorphism applied to objects Operator overloading Virtual function

3MTS 3033 - Object Oriented Programming

Page 4: Chapter 5 Polymorphism

Function overloading is a concept that allows multiple functions to share the same name with different argument types.

Function overloading implies that the function definition can have multiple forms.

Hence it can be apply on the form of polymorphism.

The following program 1.0 illustrates the use of function overloading as a form of polymorphism.

4MTS 3033 - Object Oriented Programming

Page 5: Chapter 5 Polymorphism

#include<iostream>using namespace std;int Addition(int a, int b){

int c;c=a+b;return c;

}int Addition(int d, int e, int f){

int g;g=d+e+f;return g;

}PROGRAM 1.0 Cont..

5MTS 3033 - Object Oriented Programming

Page 6: Chapter 5 Polymorphism

void main(){int i,j,k,l,m,n,p;i=4;j=6;k=Addition(i,j);cout<<endl<<"Sum of two is "<<k;l=5;m=6;n=7;p=Addition(l,m,n);cout<<endl<<"Sum of three is "<<p;

}

PROGRAM 1.0 Cont..

6MTS 3033 - Object Oriented Programming

Page 7: Chapter 5 Polymorphism

Output Program 1.0Sum of two is 10Sum of three is 18

7MTS 3033 - Object Oriented Programming

Page 8: Chapter 5 Polymorphism

The following example program 1.1 illustrates polymorphism when the choice of the form of the function depends on the type of the parameters and where the functions are member functions of a class.

8MTS 3033 - Object Oriented Programming

Page 9: Chapter 5 Polymorphism

#include<iostream>using namespace std;

class Patient{private:

int IdNumber;char Name[20];

public:Patient();Patient(int IdNumber, char Name[]);void DisplayDetails();

}; PROGRAM 1.1 Cont..

9MTS 3033 - Object Oriented Programming

Page 10: Chapter 5 Polymorphism

Patient::Patient(){cout<<"Enter Patient's Id Number "<<endl;cin>>IdNumber;cout<<"Enter Patient's Name "<<endl;cin>>Name;}Patient::Patient(int Id, char N[]){

IdNumber=Id;strcpy(Name,N);

}

PROGRAM 1.1 Cont..

10MTS 3033 - Object Oriented Programming

Page 11: Chapter 5 Polymorphism

void Patient::DisplayDetails(){cout<<endl<<"Id Number is "<<IdNumber<<" and Name is "<<Name<<endl;

}void main(){

Patient p1(10002,"John");Patient p2;p1.DisplayDetails();p2.DisplayDetails();

}

PROGRAM 1.1 Cont..

11MTS 3033 - Object Oriented Programming

Page 12: Chapter 5 Polymorphism

Output Program 1.1Enter Patient's Id Number28Enter Patient's NameAnis

Id Number is 10002 and Name is John

Id Number is 28 and Name is Anis

12MTS 3033 - Object Oriented Programming

Page 13: Chapter 5 Polymorphism

The operator overloading feature of C++ is one of the methods of realizing polymorphism.

13MTS 3033 - Object Oriented Programming

Page 14: Chapter 5 Polymorphism

General syntax declaration for operator overloading as below :ReturnType operatorX(ClassName objectName) ;

Class Name

Keyword operator

Operator arithmetic

Parameter type is class name

Argument list is object

14MTS 3033 - Object Oriented Programming

Page 15: Chapter 5 Polymorphism

General syntax definition for operator overloading as below :ReturnType ClassName::operatorX(ClassName objectName)

Class Name

Class Name

Keyword operator

Parameter type is class name

Argument list is objectScope resolution

Operator arithmetic

15MTS 3033 - Object Oriented Programming

Page 16: Chapter 5 Polymorphism

Consider the following example program 1.2 involving operations on Complex numbers consists of two parts: real and imaginary part

16MTS 3033 - Object Oriented Programming

Page 17: Chapter 5 Polymorphism

#include<iostream>using namespace std;class Complex{private:

float Real, Imaginary;public:

Complex();void GetData();Complex operator+(Complex C2); //declaration operator overloadingvoid DisplayResult();

};PROGRAM 1.2 Cont..

17MTS 3033 - Object Oriented Programming

Page 18: Chapter 5 Polymorphism

Complex::Complex(){Real=Imaginary=0.0;

}void Complex::GetData(){

cout<<"Enter Real Part :";cin>>Real;cout<<"Enter Imaginary Part :";cin>>Imaginary;

}

PROGRAM 1.2 Cont..

18MTS 3033 - Object Oriented Programming

Page 19: Chapter 5 Polymorphism

Complex Complex::operator+(Complex C){ //definition operator overloading

Complex Temp;Temp.Real=Real+C.Real;Temp.Imaginary=Imaginary+C.Imaginary;return(Temp);

}void Complex::DisplayResult(){

cout<<"Value Of Real And Imaginary After Addition"<<endl;cout<<"Real :"<<Real<<endl;cout<<"Imaginary :"<<Imaginary<<endl;

}PROGRAM 1.2 Cont..

19MTS 3033 - Object Oriented Programming

Page 20: Chapter 5 Polymorphism

void main(){Complex C1, C2, C3;cout<<"Enter Complex Number C1 :"<<endl;C1.GetData();cout<<"Enter Complex Number C2 :"<<endl;C2.GetData();C3=C1+C2; //C3=C1.operator+(C)C3.DisplayResult();

}

PROGRAM 1.2

20MTS 3033 - Object Oriented Programming

Page 21: Chapter 5 Polymorphism

Output Program 1.2Enter Complex Number C1 :Enter Real Part :10Enter Imaginary Part :23Enter Complex Number C2 :Enter Real Part :12Enter Imaginary Part :56Value Of Real And Imaginary After AdditionReal :22Imaginary :79

21MTS 3033 - Object Oriented Programming

Page 22: Chapter 5 Polymorphism

As a rule the left-hand operand is used to invoke the operator function and the right hand operand is passed as an argument to the operator function.

22MTS 3033 - Object Oriented Programming

Page 23: Chapter 5 Polymorphism

Introducing pointers to sub class Definition Virtual function Virtual function inherited Pure virtual function

23MTS 3033 - Object Oriented Programming

Page 24: Chapter 5 Polymorphism

Pointers to sub classPointers to sub class One advantage of inheritance concept

is the usage of pointer. The pointer of the super class can be used to point the object of a sub class.

See example program 1.3, how to create a pointer of the super class A to point the object of sub class B.

24MTS 3033 - Object Oriented Programming

Page 25: Chapter 5 Polymorphism

class A{ public :

int bil;

};class B : public A{ public:

int nombor;

};void main(){ A *p; create a pointer of the super class B a; create object of sub class p= &a; pointer refer/point to address of an object of sub class p->bil; valid because bil is inherit from super class p->nombor error because nombor is owned by sub class

}

PROGRAM 1.325MTS 3033 - Object Oriented Programming

Page 26: Chapter 5 Polymorphism

A super class pointer can only refer to super class member that is inherited by sub class but cannot refer to member that is only owned by sub class.

26MTS 3033 - Object Oriented Programming

Page 27: Chapter 5 Polymorphism

See example program 1.4, calculate area for square and rectangle use pointer concept.

27MTS 3033 - Object Oriented Programming

Page 28: Chapter 5 Polymorphism

#include<iostream.h>class shape{protected: int width, height;public: void set_values (int a, int b);};void shape::set_values (int a, int b) {

width=a; height=b; }class square: public shape{public:

int area (void);};int square::area (void) { return (width * height); } PROGRAM 1.4 Cont..

28MTS 3033 - Object Oriented Programming

Page 29: Chapter 5 Polymorphism

class rectangle: public shape{public:

int area (void);};int rectangle::area (void){

return (width * height ); }void main () {square s1;rectangle s2;shape *p = &s1;shape *p2 = &s2;

cout <<"Square:"<< s1.area() << endl;cout <<"Rectangle:"<< s2.area() << endl;}

p->set_values (4,5);p2->set_values (2,3);

Super class pointer (class Shape) will be used for referring members of sub class (class Square and class Rectangle)

PROGRAM 1.4

29MTS 3033 - Object Oriented Programming

Page 30: Chapter 5 Polymorphism

Output Program 1.4Square:20Rectangle:6

30MTS 3033 - Object Oriented Programming

Page 31: Chapter 5 Polymorphism

Example 1.4 describes how super class pointer used to access members in the sub class. There are 3 classes, which are Shape, Square and Rectangle.

Square s;Rectangle t;

Shape *p = &s;Shape *p2 = &t;

p->set_values (4,5);p2->set_values (2,3);

Refer to set_values() in SquareRefer to set_values() in Rectangle

31MTS 3033 - Object Oriented Programming

Page 32: Chapter 5 Polymorphism

Pointer from the super class can be used to refer to the member inherited by sub class. For example: super class pointer can refer to method set_values() inherited by both class which are Square and Rectangle class from Shape class.

32MTS 3033 - Object Oriented Programming

Page 33: Chapter 5 Polymorphism

It is a method declared in super class and declared once again in sub class.

To create a virtual function, begin virtual declaration with the keyword virtual.

When virtual function is defined once again by sub class, the keyword virtual is not required to be repeated (There would not be any error if the keyword virtual is used).

33MTS 3033 - Object Oriented Programming

Page 34: Chapter 5 Polymorphism

The special thing about virtual function is that it can be referred by using super class pointer even it is a member of the sub class (not inherited from super class).

Classes that contain virtual function are said to be polymorphic.

An example of virtual function declaration is as follows:

virtual void func ( );

34MTS 3033 - Object Oriented Programming

Page 35: Chapter 5 Polymorphism

The usage of virtual function is to make programming easier. By defining a virtual function, super class seems to provide all specific elements that can be used by classes. Indirectly, it will provide a common interface between all the sub classes.

35MTS 3033 - Object Oriented Programming

Page 36: Chapter 5 Polymorphism

Virtual keywords will make a compiler revise whether a sub class defines virtual function on its own to be used in its class.

If yes, virtual function in sub class will be used. But then, if sub class didn’t define its own virtual function, virtual function inherited from the super class will be used.

36MTS 3033 - Object Oriented Programming

Page 37: Chapter 5 Polymorphism

See example program 1.5 to Calculate area for rectangle and triangle.

37MTS 3033 - Object Oriented Programming

Page 38: Chapter 5 Polymorphism

#include <iostream.h>class Shape { protected: int length, width; public:

void set_value (int a, int b); virtual void area() {

cout<<"No calculation for area here\n"; }

};void Shape::set_value(int a, int b){length=a; width=b;}

PROGRAM 1.5 Cont..

38MTS 3033 - Object Oriented Programming

Page 39: Chapter 5 Polymorphism

class Rectangle: public Shape {public:

void area () ; };void Rectangle:: area () {

cout<<"The area of rectangle is ";cout<<length*width<<endl;

}

class Triangle: public Shape {public:

void area ()};void Triangle::area () { cout<<"The area of triangle is ";cout<<(length * width)/2<<endl; }

PROGRAM 1.5 Cont..

39MTS 3033 - Object Oriented Programming

Page 40: Chapter 5 Polymorphism

void main () { int length, width; Shape * b; Rectangle four;Triangle three; cout<<"Enter length:"; cin>>length; cout<<"Enter width:"; cin>>width;

}  PROGRAM 1.5

b=&four; b->set_value(length, width); b->area();

b=&three; b->set_value(length,width); b->area();

1

2

40MTS 3033 - Object Oriented Programming

Page 41: Chapter 5 Polymorphism

Output Program 1.5Enter length:3Enter width:5The area of rectangle is 15The area of triangle is 7

41MTS 3033 - Object Oriented Programming

Page 42: Chapter 5 Polymorphism

1Pointer b (from super class) refers to the method set_value() and area()owned by Rectangle class.

2Pointer b (from super class) refers to set_value() and area() method; which is ownedby Triangle class.

42MTS 3033 - Object Oriented Programming

Page 43: Chapter 5 Polymorphism

EXPLANATION Program 1.5 In super class Shape, the function area() is declared as virtual.This

means that the area function can be declared once again in sub class with the same name.

In Rectangle and Triangle, area() has been declared once again based on the requirement of that class.

In the beginning, b is given the address of four and method set_value() and method area() is called.

C++ will determine area() version that will be referred to by looking at what is pointed by b.

In this case, b points to the object Rectangle, so the area() in Rectangle will be executed.

As mentioned earlier, a super class pointer can point to any object inherited from the super class.

When area() is called again by b pointer, C++ will check which object is referred to currently. Based on this, the suitable version of area() will be determined.

Since b refers to Triangle , area() version in Triangle will be used.

43MTS 3033 - Object Oriented Programming

Page 44: Chapter 5 Polymorphism

Virtual function Virtual function inheritedinherited

When virtual function is inherited, all virtual characteristics will also be inherited. If sub class does not have its own version of virtual function, virtual function in the super class will be used.

Example program 1.6 apply the use of virtual function in inheritance.

44MTS 3033 - Object Oriented Programming

Page 45: Chapter 5 Polymorphism

#include <iostream.h>class A {private:

int x;public:

virtual void f() { cout << "Inside A::f\n"; }

};class B : public A { private:

int y; public:

virtual void f() { cout << "Inside B::f\n"; }

};

PROGRAM 1.6 Cont..

45MTS 3033 - Object Oriented Programming

Page 46: Chapter 5 Polymorphism

class C : public B {private:

int z;public:

virtual void f() { cout << "Inside C::f\n"; }

};int main () {A a_obj;B b_obj;C c_obj; A* a_ptr = &a_obj;a_ptr->f();a_ptr = &b_obj;a_ptr->f();a_ptr = &c_obj;a_ptr->f();return 0;} PROGRAM 1.6

46MTS 3033 - Object Oriented Programming

Page 47: Chapter 5 Polymorphism

Output Program 1.6Inside A::fInside B::fInside C::f

47MTS 3033 - Object Oriented Programming

Page 48: Chapter 5 Polymorphism

See example 1.7, shows the uses of virtual function in inheritance.

#include <iostream.h>class Shape {protected:

int length, width;public:void set_value (int a, int b);virtual void display(){

cout<<"No calculation in this area\n";}};void Shape::set_value (int a, int b){

length=a;width=b;

} PROGRAM 1.7 Cont..

48MTS 3033 - Object Oriented Programming

Page 49: Chapter 5 Polymorphism

class Rectangle: public Shape { int area; public: void calculate_area ();

void display();}; void Rectangle::calculate_area () {

area=length*width; }

void Rectangle:: display() {

cout<<"The area of Rectangle is="<<area;cout<<'\n';

}

PROGRAM 1.7 Cont..

49MTS 3033 - Object Oriented Programming

Page 50: Chapter 5 Polymorphism

class Triangle: public Shape {int area; public:

void calculate_area ();/* No declaration for void display() in this class */};void Triangle::calculate_area () {

area=(length * width)/2; }void main () {int length, width;Shape * b;Rectangle four;Triangle three;

PROGRAM 1.7 Cont..

50MTS 3033 - Object Oriented Programming

Page 51: Chapter 5 Polymorphism

cout<<"Enter length:";cin>>length;cout<<"Enter width:";cin>>width;b=&four;b->set_value(length, width);four.calculate_area();b->display();b=&three;b->set_value(length,width);three.calculate_area();b->display();}Output Program 1.7Enter length:5Enter width:8The area of Rectangle is=40No calculation in this area

PROGRAM 1.7

51MTS 3033 - Object Oriented Programming

Page 52: Chapter 5 Polymorphism

Since Triangle class doesn’t define virtual function (void display()), so the compiler will execute the inherited virtual function.

In example 3, the implementation of virtual function will cause problem to arise when the sub class does not define its own version of virtual function.

52MTS 3033 - Object Oriented Programming

Page 53: Chapter 5 Polymorphism

Compiler will execute the virtual function in the super class that sometimes produce unrelated output like what happened in example 3.

So, it is better that the super class make it compulsory for all the sub class to have its own version of virtual function by declaring pure virtual function.

53MTS 3033 - Object Oriented Programming

Page 54: Chapter 5 Polymorphism

Pure virtual function is a function declared in the super class and makes it compulsory for all sub class to define their own function based on their context.

If sub class fails to do so, an error message will appear.

54MTS 3033 - Object Oriented Programming

Page 55: Chapter 5 Polymorphism

See example program 1.8, which is implement the concept of pure virtual function.

The syntax of declaration pure virtual function is as below :super class{……….public:

virtual types function-name(list of parameter)=0;……….};

55MTS 3033 - Object Oriented Programming

Page 56: Chapter 5 Polymorphism

#include <iostream.h>class Shape {protected:

int length, width;public:

void set_value (int a, int b);virtual void display()=0;

};void Shape::set_value (int a, int b){

length=a;width=b;

}class Rectangle: public Shape { int area;public:

void calculate_area ();void display();

};PROGRAM 1.8 Cont..

56MTS 3033 - Object Oriented Programming

Page 57: Chapter 5 Polymorphism

void Rectangle::calculate_area () { area=length*width; }void Rectangle::display() { cout<<"The area of Rectangle is="<<area<<endl; }class Triangle: public Shape { int area; public: void calculate_area (); void display();};

PROGRAM 1.8 Cont..

57MTS 3033 - Object Oriented Programming

Page 58: Chapter 5 Polymorphism

void Triangle::calculate_area () {area=(length * width)/2; } void Triangle::display() { cout<<"The area of Triangle is="<<area<<endl; }void main () { int l, w;Shape * b;Rectangle four;Triangle three;cout<<"Enter length:";cin>>l;cout<<"Enter width:";cin>>w;

PROGRAM 1.8 Cont..

58MTS 3033 - Object Oriented Programming

Page 59: Chapter 5 Polymorphism

b=&four;b->set_value(l, w);four.calculate_area();b->display();b=&three;b->set_value(l,w);three.calculate_area();b->display ();}

PROGRAM 1.8

59MTS 3033 - Object Oriented Programming