You are on page 1of 39

C++ permits us to add two variables of userdefined types with the same syntax that is applied to the basic

types.C++ has the ability to provide special meaning for a data type. The mechanism of giving such a special meaning to an operator is known as operator overloading

The operator overloading feature is one of the method realizing Polymorphism. Operator overloading allows to provide additional meaning to already existing operator. Operator overloading extends the semantics of an operator without changing its syntax. Precedence and associativity remains same for overloaded operators. Overloaded operator should not change its original meaning.

Operator can be unary or binary operator.

Operators that cannot be overloaded

Operators that cannot be overloaded

. .* :: ?:

Cannot create new operators.

Operators must be overloaded explicitly.

Overloading + and = does not overload +=

Operator ?: cannot be overloaded.

When an operator is overloaded We cannot change its syntax The grammatical rules that govern its use such as :
No of operands Precedence and Associativity

For example: the multiplication operator will enjoy higher precedence than the addition operator.

return type classname:: operator(op-arglist) { functon-body }

return type is the type of value returned by the specified operation. op is the operation being overloaded. Operator function must be either memberfunction or friend function.

Friend Function(ff)

Argument for unary operators. 2) A ff will have two argument for binary operators.

A ff will have only one

Member Function(mf) 1) A mf function will have no arguments for unary operators. 2)A mf will have only one argument for binary operators. because object used to invoke the mf is passed implicitly therefore is available for mf

This is not case with friend function. Arguments may be passed either by value or reference.

vector operator+(vector);
vector operator-();

//vector addition

// unary minus

friend vector operator+(vector,vector);//vector additn

friend vector operator-(vector); // unary minus int operator==(vector); // comparison

vector is a data type of class

friend int operator==(vector,vector); //comparison

Create a class that defines the data type that is to be used in overloading operation. Declare the operator function operator op() in the public part of the class. It may be either friend function or member function. Define the operator function to implement the required operations.

A minus operator when used as unary, takes just one operand. Minus operator changes the sign of an operand when applied to basic data item.

Now we will see how to overload this operator so that it can be applied to an object in much the same way as applied to an int or float.

The unary minus when applied to an object should change the sign of each data items.

#include<iostream.h> class space Output { S: 10 -20 30 int x,y,z; S: -10 20 -30 . public: void getdata(int a,int b,int c); void display(); void operator-(); // overload unary minus }; void space :: getdata(int a,int b,int c) int main() { { space S; x=a; S.getdata(10,-20,30); y=b; z=c; cout<<S:; } S.display(); void space :: display() { -S; //activates operator minus function cout<<x<<y<<z; } cout<<S:; void space :: operator-() S.display(); { x=-x; return 0; y=-y; } z=-z;

It is possible to overload a unary minus operator using friend functions follows:

friend void operator-(space &s); //declaration friend void operator-(space &s) //definition { s.x = -s.x; s.y = -s.y; s.z = -s.z; }

Overloading Binary Operators: How to add two complex numbers

A statement like: C=sum(A , B); // functional notation was used. the fnal notation can be replaced by a natural looking expression: C=A+B; //arithmetic notation.

By overloading the + operator using an operator+() function.

#include<iostream.h> class complex { float x; float y; public: complex(); complex(float real,float imag) { x=real; y=imag; } complex operator+(complex); void display(); }; complex complex :: operator+(complex c) { complex temp; temp.x= x + c.x; temp.y= y + c.y; return(temp); } void complex :: display() { cout<<x<<y; }

int main() { complex c1,c2,c3; c1= complex(2.5, 3.5); c2 = complex(1.6, 2.7); c3=c1+c2;

cout<<c1=<<c1; cout<<c2=<<c2; cout<<c3=<<c3; return 0;

} It receives only one value as argument. Where does the other value come from? We know that a member function can be invoked only by an object of the same class.Here,the object C1 takes the responsibility of invoking the fn and C2 plays the role an argument that is passed to the function.

#include <iostream.h> class Exforsys { private: int x; int y; public: Exforsys() //Constructor { x=0; y=0; } Exforsys(int a,int b) //Constructor { x=a; y=b; } void getvalue( ) //Member Function for Inputting values { cout << \n Enter value for x: ; cin >> x; cout << \n Enter value for y: ; cin>> y; }

void displayvalue( ) //Member Function { cout <<value of x is: << x <<; value of y is: <<y } Exforsys operator +(Exforsys); }; Exforsys Exforsys :: operator + (Exforsys e2) //Binary operator overloading for + operator defined { int x1 = x+ e2.x; int y1 = y+e2.y; return Exforsys(x1,y1); }

void main( ) { Exforsys e1,e2,e3; //Objects e1, e2, e3 created cout<<\nEnter value for Object e1:; e1.getvalue( ); cout<<\nEnter value for Object e2:; e2.getvalue( ); e3= e1+ e2; //Binary Overloaded operator used cout<< \nValue of e1 is:<<e1.displayvalue(); cout<< \nValue of e2 is:<<e2.displayvalue(); cout<< \nValue of e3 is:<<e3.displayvalue(); }

#include <iostream.h> class Example { private: int count; public: Example() : count(0) {} Example(int c) : count(c) {} void getcount() { cout<<count; }


// Parametrized Constructor

Example operator ++(Example); }; Example Example :: operator ++ (void) //unary operator overloading for ++ operator defined { int c; c = ++count; return Example(c); } Int main() { Example c1(100), c2,c3; c3 = ++c1; c3.getcount(); C3 = ++c2; c3.getcount(); return 0; }

Classes and Objects Operator Overloading and Friend Functions // OPERATOR: an operator function for vector addition #include <iostream.h> class vector { public: vector(float xx=0, float yy=0) { x = xx; y = yy; } void printvec()const; void getvec(float &xx, float &yy)const { xx = x; yy = y; } private: float x, y; };

Use operator overloading to improve readability

Avoid excessive or inconsistent usage

Write function definition as normal Function name is keyword operator followed by the symbol for the operator being overloaded. operator+ would be used to overload the addition operator (+)

#include <iostream.h> class Index { private: int value; public: Index() : value(0) {} Index(int c) : value(c) {} int getindex() { return value; }


// Parametrized Constructor

Index operator++() { value = value+1; return Index(value); } }; Void main() { Index idx1, idx2; Cout<<idx1.getindex(); Cout<<idx2.getindex(); Idx1 = ++idx2; Idx2++; Cout<<idx1.getindex(); Cout<<idx2.getindex(); }

When we return a nameless temporary object, there must be a parameterized constructor in the class definition. Index(int value) { value = val; }

The prefix notation causes a variable to be updated before its value is used. ++X The postfix notation causes it to be updated after its value is used. X++ But in our program the statements Idx1 = idx2++; & idx1 = ++idx2; have same effect.

C++ provides additional syntax to express and distinguish between prefix and postfix overloaded operator function. A new syntax for indicating postfix operator overloading is used operator ++ ( int )

#include <iostream.h> class Index { private: int value; public: Index() : value(0) {} Index(int c) : value(c) {} int getindex() { return value; }


// Parametrized Constructor

Index operator++ () { return Index(++value); } Index operator++ ( int ) { return Index(value++); } }; Void main() { Index idx1(2), idx2(2), idx3, idx4; Cout<<idx1.getindex(); Cout<<idx2.getindex(); Idx3 = idx1++; Idx4 = ++Idx2; Cout<<idx1.getindex(); Cout<<idx2.getindex(); Cout<<idx3.getindex(); Cout<<idx4.getindex(); }

Representing the same data in multiple forms involves the conversion of data from one form to another. For example Degree = Radian Or Radian = Degree In C++, implicit conversion is achieved by overloading the assignment operator. Var1 = Var2 Obj1 = Obj2 + Obj3 This is applicable for basic data types and user defined data types.

Example int I; float F; F = I; // Conversion from integer to float I = F; // Conversion from float to integer The compiler calls the special routine to convert these values. This feature of compiler is known as implicit type conversion.

Explicit conversion using typecast operator F = (float) I; Or F = float (I);

User can not rely on the compiler to perform conversion from user defined to primitive data types and vise-versa. Basic type to user defined conversion Constructor(Basic Type) { // steps for converting basic type to // object attributes }

User defined type to Basic type conversion: achieved through operator function, which must be defined as overloaded basic data type with no argument. operator BasicType() { // steps for converting object attributes // to basic data types }

#include <iostream.h> class Meter { private: float length; public: Meter() //Constructor { length = 0.0 ; } Meter(float initlength) //Parametrized Constructor { length = initlength / 100.0 ; // cm to meter } operator float() { float lengthCms; lengthCms = length * 100.0 ; // meter to cm return (lengthCms); }

Void getlength() { cout<< \n Enter length in meters: ; Cin>>length; } Void showlength() { cout<< Length in meters: = << length; } };

Void main() { Meter meter1; float length 1; cout<< Enter length in in Cms; Cin>> length1; meter1 = length1; // basic to class type meter1.showlength(); Meter meter2; float length2; meter2.getlength(); length2 = meter2; // class type to basic cout<< length in meters = <<length2; }