1 / 59

Polymorphism and Operator Overloading in C++

Learn the concepts of polymorphism & operator overloading in C++, including compile-time & run-time polymorphism, function overloading, pitfalls, and best practices. Get insights from Vishwakarma Institute of Information Technology, Pune.

hainesd
Download Presentation

Polymorphism and Operator Overloading in C++

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Contents • Operator Overloading • Concept of overloading • operator overloading • Overloading Unary Operators • Overloading Binary Operators, • Data Conversion • Type casting (implicit and explicit) • Pitfalls of Operator Overloading and Conversion • Keywords explicit and mutable Vishwakarma Institute of Information Technology,Pune

  2. Contents • Polymorphism • concept • relationship among objects in inheritance hierarchy • abstract classes • polymorphism Vishwakarma Institute of Information Technology,Pune

  3. Polymorphism • Means one name multiple forms Polymorphism Compile time Run time Operator overloading Function overloading Virtual functions Vishwakarma Institute of Information Technology,Pune

  4. Polymorphism • Important feature of Object Oriented programming • Can be implemented with concepts like operator overloading, function overloading and virtual function • Selecting the appropriate overloaded function by the compiler is know as early binding(static binding) • Classification of polymorphism can be done on the basis of time at which object is bind to function. Vishwakarma Institute of Information Technology,Pune

  5. Compile time(early binding) • The overloaded member functions are selected for invoking based on their type and no. of arguments at compile time. This is called early binding or static binding or static linking or compile time polymorphism • Early binding means an object is bound to its function call at compile time Vishwakarma Institute of Information Technology,Pune

  6. Run time(late binding) • To select which function should be invoked at run time, the concept is known as run time polymorphism • In run time polymorphism the function call is linked with the appropriate object much later after compilation, process is termed as late binding • also called as dynamic binding Vishwakarma Institute of Information Technology,Pune

  7. Overloading occurs when the same operator or function name is used with different signatures(in different form) • for e.g. +/*/- used to do different behavior than usual. • Both operators and functions can be overloaded in C++ Vishwakarma Institute of Information Technology,Pune

  8. Need of overloading • To make sure that the operator performs more operations at different instances. • To make user defined data types work as standard data types, use operator overloading. • int, float directly can be added what about adding two objects ?? • The motivation behind function overloading is to be able to use similar function calls to functions that essentially do the same thing, but process different data types Vishwakarma Institute of Information Technology,Pune

  9. Function overloading • Function Overloading is the ability to have multiple functions with the same name, but with different signatures. • C++ supports writing more than one function with the same name but different argument lists. This could include: • different data types • different number of arguments • The advantage is that the same apparent function can be called to perform similar but different tasks. Vishwakarma Institute of Information Technology,Pune

  10. Function overloading • Function having same name different signatures e.g. int add(int a, int b); float add(float c, float d); long add(long e, long f); void main() { int a=10, b=20,sum_int; float c= 20.5, d=20.5,sum_float long int e =1000, f =2000,sum_long; sum_int = add(a,b); sum_float = add(c,d); sum_long = add(e,f); } Vishwakarma Institute of Information Technology,Pune

  11. Function definitions int add(int a, int b){ return a+b; } float add(float c, float d){ return c+d; } long add(long e, long f){ return e+f; } Vishwakarma Institute of Information Technology,Pune

  12. Operator Overloading • C++ already has a number of types (e.g., int, float, char, etc.) that each have a number of built in operators. For example, a float can be added to another float and stored in yet another float with use of the + and = operators: float C = float A + float B; • Operator overloading means that the operators: • Have multiple definitions that are distinguished by the types of their parameters, and • When the operator is used, the C++ compiler uses the types of the operands to determine which definition should be used. Vishwakarma Institute of Information Technology,Pune

  13. Operator overloading(cntd…) • Overloaded operators should exhibit the functionality of their built-in counterparts • E.g. the + operator should be overloaded to perform addition, not subtraction. Avoid excessive or inconsistent use of operator overloading, as this can make a program difficult to read. Vishwakarma Institute of Information Technology,Pune

  14. Restrictions on operator overloading • Cannot create new operators • Cannot change • Precedence of operator (order of evaluation) • Use parentheses to force order of operators • Associativity (left-to-right or right-to-left) • Number of operands • e.g., & is unary, can only act on one operand • How operators act on built-in data types (i.e., cannot change integer addition) • Meaning of the operator remains same, it will still do same operation but with different arguments Vishwakarma Institute of Information Technology,Pune

  15. Operators can be overloaded Vishwakarma Institute of Information Technology,Pune

  16. Operators can not be overloaded • Class member access operator ( . ) • Scope resolution operator( :: ) • Pointer to member operator (.*) • Conditional operator(?:) • Size of operator(sizeof) Vishwakarma Institute of Information Technology,Pune

  17. Definition of operator overloading • Operator function is used • Syntax : Return type class name :: operator op(arg-list) { Function body // task goes here } Vishwakarma Institute of Information Technology,Pune By: P. V. Khandare

  18. Operator overloading • Operator overloading can be done by implementing a function which can be : • Member Function • Non-Member Function • Friend Function • In member functions being operator function, function takes noargument in case of unary operator and one argument in case of binary operator • In friend functions being operator function, function takes one argument in unary operator and two argument in Binary Operator Vishwakarma Institute of Information Technology,Pune By: P. V. Khandare

  19. Examples of Unary operators : • The increment (++) and decrement (--) operators. • The unary minus (-) operator. • The logical not (!) operator. • The unary operators operate on the object for which they were called and normally, this operator appears on the left side of the object, as in !obj, -obj, and ++objbut sometime they can be used as postfix as well like obj++ or obj--

  20. Example vector operator+(vector);  // binary addition vector operator-(); // unary minus friend vector operator+( vector, vector ); // binary addition friend vector operator-( vector ); // unary minus vector operator-( vector &a ); // binary subtraction intoperator ==(vector); // binary comparison friendintoperator ==(vector, vector); // binary comparison Vishwakarma Institute of Information Technology,Pune By: P. V. Khandare

  21. Overloading unary operator(using member function ) Void data : display() { cout<<x<<“ “ ; cout<<y<<“ “ ; } Void data : operator-(){ x = -x; y = -y; } int main() { data d; d.get(10, -20); cout<< “d : “; d.display(); -d; // activate operator funcn cout<<“ d : “; d.display(); return 0; } Class data { int x,y; public : void get(int a, int b); void display(); void operator-(); }; Void data : get(int a, int b) { x = a; y = b; }

  22. int main() { Distance D1(11, 10), D2(-5, 11); -D1; // apply negation D1.displayDistance(); //display D1 -D2; // apply negation D2.displayDistance(); // display D2 return 0; } class Distance { private: int feet; // 0 to infinite int inches; // 0 to 12 public: // required constructors Distance() { feet = 0; inches = 0; } Distance(int f, int i) { feet = f; inches = i; } // method to display distance void displayDistance() { cout << "F: " << feet << " I:" << inches <<endl; } // overloaded minus (-) operator Distance operator- () { feet = -feet; inches = -inches; return Distance(feet, inches); } }; Output : F: -11 I:-10 F: 5 I:-11

  23. void time::getTime() { cout<<"\n Enter the hour(0-11) "; cin>>h; cout<<"\n Enter the minute(0-59) "; cin>>m; cout<<"\n Enter the second(0-59) "; cin>>s; } void main() { clrscr(); time t1,t2,t3; cout<<"\n Enter the first time "; t1.getTime(); cout<<"\n Enter the second time "; t2.getTime(); t3=t1+t2; //adding of two time object using '+' operator cout<<"\n First time "; t1.show(); cout<<"\n Second time "; t2.show(); cout<<"\n Sum of times "; t3.show(); getch(); } #include< iostream.h> #include< conio.h> class time { int h,m,s; public: time() { h=0, m=0; s=0; } void getTime(); void show() { cout<< h<< ":"<< m<< ":"<< s; } time operator+(time);//overloading '+' operator }; time time::operator+(time t1)//operator function { time t; int a, b; a=s+t1.s; t.s=a%60; b=(a/60)+m+t1.m; t.m=b%60; t.h=(b/60)+h+t1.h; t.h=t.h%12; return t; }

  24. Overloading Relational operator • You can also overload Relational operator like == , != , >= , <= etc. to compare two user-defined object.

  25. class time { int hr,min,sec; public: time() ////Constructor { hr=0, min=0; sec=0; } time(int h,int m, int s) //Constructor { hr=h, min=m; sec=s; } friend bool operator==(time &t1, time &t2);//overloading '==' operator }; bool operator== (time &t1, time &t2) //operator function { return ( t1.hr == t2.hr && t1.min == t2.min && t1.sec == t2.sec ); }

  26. Unary operator overloading using Friend function void operator-(UnaryFriend &x){     x.a = -x.a;     //Object name must be used as it is a friend function     x.b = -x.b;     x.c = -x.c;}int main(){     UnaryFriend x1;     x1.getvalues();     cout<<"Before Overloading\n";     x1.show();     cout<<"After Overloading \n";     -x1;      x1.show();      return 0;} #include<iostream>using namespace std;class UnaryFriend{     int a=10;     int b=20;     int c=30;     public:         void getvalues()         {              cout<<"Values of A, B & C\n";              cout<<a<<"\n"<<b<<"\n"<<c<<"\n"<<endl;         }         void show()         {              cout<<a<<"\n"<<b<<"\n"<<c<<"\n"<<endl;         }void friend operator-(UnaryFriend &x);      };

  27. Output:Values of A, B & C102030Before Overloading102030After Overloading-10-20-30

  28. Overloading binary operator( member function ) void main() { complex C1,C2,C3 C1=complex(2.5,3.5); C2=complex(1.5,2.5); C3=C1+C2; C1.Display; C2.display(); C3.display(); } Output : 2.5+3.5j 1.5+2.5j 4.0+6.0j Class complex { float x, y; public : // other functions complex operator+(complex ); }; complex complex :: operator+(complex c) { complex temp; temp.x=x+ c.x; temp.y=y+c.y; return(temp); }

  29. int main() { demo d1(2,3); demo d2(4,5); demo d3; d3 = d1 + d2; cout<<"Object C1\n"; d1.display(); cout<<"Object C2\n"; d2.display(); cout<<"Object C3\n"; d3.display(); return 0; } Output:Object C1 X=2 Y=3 Object C2 X=4 Y=5 Object C3 X=6 Y=8 #include <iostream.h> class demo { intx,y; public: demo() { x=0; y=0; } demo(int a, int b) { x=a; y=b; } demo operator +(demo &d) { demo d3; d3.x = x + d.x; d3.y = y + d.y; return d3; } void display() { cout<<"X="<<x<<endl; cout<<"Y="<<y<<endl; } };

  30. Values Values::operator-(Values p2)          {               Values temp;                temp.a =a -p2.b;                temp.b =a -p2.b;                return temp;           }               Values Values::operator=(Values p2)          {                a =p2.a;                b =p2.a;                return *this;           }               Values Values::operator++()          {               a++;               b++;               return *this;           } #include <iostream.h>#include<conio.h>class Values{inta,b; public: Values(){} Values(intaa, int bb) { a= aa; b= bb; } void show() {cout <<a<<" ";cout <<b<<"\n"; } friend Values operator+(Values p1 ,Values p2); Values operator-(Values p2);Values operator=(Values p2);Values operator++();};//Now,+is overloaded using friend function. Values operator+(Values p1 ,Values p2) { Values temp;temp.a =p1.a +p2.a;temp.b =p1.b +p2.b; return temp; }

  31. void main()          {clrscr();               Values v1 (20,30),v2(15,40);               v1.show();               v2.show();               ++v1;               v1.show();               v2 =++v1 ;               v1.show();               v2.show();               v1=v2;               v1.show();               v2.show();getch();         }

  32. Type Conversion • C++ is a strong-typed language. Many conversions, specially those that imply a different interpretation of the value, require an explicit conversion, known in C++ as type-casting. • Type conversion: The process of converting one pre defined type to another type is called type conversion. • TYPE CONVERSION IS OF TWO TYPE • 1.IMPLICIT. • 2.EXPLICIT.

  33. IMPLICIT CONVERSION :Implicit conversion is when compiler automatically converts one predefined data type to another data type. #include<iostream> using namespace std; main()  {  int x;  float y=55.7;  x=y; // type conversion takes place  cout<<y;  return 0;  }

  34. Implicit conversion takes place from int data type to float data type. include<iostream> using namespace std; main() { inta=35; float b; b=a;//type conversion from float to intcout<<"the value of b is "<<b; return 0; }

  35. EXPLICIT CONVERSION : • Explicit type conversion is a type conversion which is done explicitly(i.e) by the user instead of leaving it up to compiler to perform automatically. • This is also called as Type casting. Where we specifically converts one operand of different data type to another operand of different type.

  36. Conversion from basic to class type Time t1; // class Time has hours and mins int duration = 100; T1 = duration; • Class type to basic type operator typename(){ } vector : operator double( ){ } double length = V1; or double length = double(V1); • One class type to another class type • Both ways

  37. Type conversion(Cont…) • ‘=‘ is a very special operator having complex properties. • We know that = operator assigns values form one variable to another or assigns the value of user defined object to another of the same type. For example int x, y ; x = 100; y = x; Here, first 100 is assigned to x and then x to y.

  38. Type conversion(Cont..) Consider another statement, t3 = t1 + t2; • This statement assigns the result of addition, which is of type time to object t3 also of type time. • So the assignments between basic types or user defined types are taken care by the compiler provided the data type on both sides of = are of same type. • But what to do in case the variables are of different types on both sides of the = operator?

  39. Type conversion(Cont..) Three types of situations might arise for data conversion between different types : (i) Conversion from basic type to class type :the left-hand operand of = operator is always a class object. Hence, we can also accomplish this conversion using an overloaded = operator. (ii) Conversion from class type to basic type. (iii) Conversion from one class type to another class type.

  40. Conversion form basic type to class typeclass time{   int hours;   int minutes;   public :   void time ( int t )   // II constructor   {     hours = t / 60 ;    // t is inputted in minutes     minutes = t % 60 ;   }};In the following conversion statement :-   time t1;    // object t1 created   int period = 160;   t1 = period;   // int to class type

  41. The object t1 is created. The variable period of data type integer is converted into class type time by invoking the constructor. After the conversion, the data member hours of t1 will have value 2 and minutes will have a value of 40 denoting 2 hours and 40 minutes.Note that constructors are used for the type conversion take a single argument whose type is to be converted.

  42. int main() { cout <<"Float to distance conversion.\n**\n"; float meters; cout<<"Enter values in meter:"; cin >>meters; Distance distance = meters; distance.displaydist();} #include <iostream> using namespace std; const float MeterToFloat=3.280833; class Distance { int feets; float inches; public: Distance() //Distance Constructor { feets=0;inches=0.0; } Distance(float numofmeters) //Single Parameter constructor { float feetsinfloat= MeterToFloat * numofmeters; feets=int(feetsinfloat); inches=12*(feetsinfloat-feets); } void displaydist() // Method to display converted values { cout<<"Converted Value is: "<<feets<<"\' feets and "<<inches<<'\"'<<" inches."; } };

  43. First look at the Distance class. It has two member variables: integer type feets and float type inches. It has a no argument constructor which will initialize the values of feets and inches to 0 and 0.0 respectively. Next, it has a constructor that takes a float type variable as an argument. Inside this constructor we multiply the passed float type variable with 3.280833 which is stored in constant MeterToFloat variable which has been defined constant in the beginning of the program. We are multiplying the passed float parameter with this number because passed variable will contain meters. And one meter contains 3.280833. In our distance class we have distance in feet and inches, therefore we converted the float to feet. Then we truncated the decimal part of the feet using feets=int(feetsinfloat);

  44. This is another way to explicitly convert basic types, simple add the data type followed by the value in round brackets.Now, feets contain value in integer. But we want the inches part as well to be stored in inches variable. Therefore we subtracted the feets which is integer part from the actual feetinfloat variable that contains the complete converted value in feet. We multiplied the result with 12 to get exact figure in inches because one foot contains 12 inches. This the logic that will convert our float variable that contain meters to Distance variable which contain feet and inches.Next, we have simply added a method which displays the converted feet and inches to the output screen.Now come inside the main method, real magic begins there. We have declared a variable of type float, named meters. We ask the user to enter the distance in meters. User will enter the distance and using the below statement. Distance distance = meters;

  45. We will convert a float type basic variable to a user defined type class variable. This was not possible explicitly therefore we had to write code to achieve the desired functionality. Now, when users enter the distance in meters, it will give back the result in corresponding number of feet and inches. The output of Example3 is as follows. Output3

  46. Class Type to Basic Type • For conversion from a basic type to class type, the constructors can be used. But for conversion from a class type to basic type constructors will not work. • In C++, we have to define an overloaded casting operator that helps in converting a class type to a basic type. • The syntax of the conversion function is given below: Operator typename () { ....... ....... //statements }

  47. Class Type to Basic Type(Cont) matrix :: operator float () { float sum = 0.0; for(int i=0;i<m;i++) { for (int j=0; j<n; j++) sum=sum+a[i][j]*a[i][j]; } Return sqrt(sum); //norm of the matrix } • Here, the function converts a class type data to typename. • For example, the operator float ( ) converts a class type to type float • the operator int ( ) converts a class type object to type int. For example,

  48. Class Type to Basic Type • Here, the function finds the norm of the matrix (Norm is the square root of the sum of the squares of the matrix elements). We can use the operator float ( ) as given below : float norm = float (arr); or float norm = arr; where arr is an object of type matrix. When a class type to a basic type conversion is required, the compiler will call the casting operator function for performing this task. The following conditions should be satisfied by the casting operator function : (a) It must not have any argument (b) It must be a class member (c) It must not specify a return type

  49. For example suppose we want to assign time in hours and minutes in the form of total time in minutes into one integer variable “duration” then we can write the type conversion function as under: class Time { int hrs,min; public: Time(int ,int); // constructor operator int(); // casting operator function };  Time::Time(int a,int b) { cout<<"Constructor called with two parameters..."<<endl; hrs=a; min=b; }

  50. Time :: operator int() //destination cast type { cout<<"Class Type to Basic Type Conversion..."<<endl; return(hrs*60+min); } void main() { int h,m,duration; cout<<"Enter Hours "; cin>>h; cout<<"Enter Minutes "; cin>>m; Time t(h,m); // construct object duration = t; // casting conversion OR duration = (int)t cout<<"Total Minutes are "<<duration; cout<<"2nd method operator overloading "<<endl; duration = t.operator int(); cout<<"Total Minutes are "<<duration; getch(); }

More Related