2. Contents
Operator Overloading
Overloading Unary and Binary Operator
Overloading using friend function
Type casting andType conversion
3. Quiz 1
What is Operator Overloading?
Operator overloading is a specific case of
polymorphism in which some or all operators like +,
= or == are treated as polymorphic functions and as
such have different behaviours depending on the types
of its arguments.
4. Operator Overloading
Operator overloading is a specific case of polymorphism in which
some or all of operators like +, =, or == have different
implementations depending on the types of their arguments.
Operator overloading gives us the opportunity to redefine the
C++ language.
C++ permits us to add two variables of user defined types with
the same syntax that is applied to the basic data types.
5. Restrictions on Operator Overloading
Overloading restrictions
Precedence of an operator cannot be changed
Associatively of an operator cannot be changed
Arity (number of operands) cannot be changed
Unary operators remain unary, and binary operators remain binary
Operators &, *, + and - each have unary and binary versions
Unary and binary versions can be overloaded separately
No new operators can be created
Use only existing operators
No overloading operators for built-in types
Cannot change how two integers are added
Produces a syntax error
6. Restrictions on Operator Overloading
Following operators can’t be overloaded:
Class member access operators (., .*)
Scope resolution operator (::)
Size operator (sizeof )
Conditional operator (?:)
All other operators can be overload
7. Defining Operator Overloading
General syntax for operator overloading is:
return type classname :: operator op(arglist)
{
Function body
}
For e.g.:
vector operator +(vector);
vector is a data type of class.
8. Operator Overloading Process
The process of overloading involves the following steps:
Create a class that defines the data type that is to be used in the
overloading operation.
Declare the operator function operator op() in the public part
of the class.
Define the operator function to implement the required
operations.
9. Overloading Unary Operators
Consider unary minus operator (changes the sign of the
operand)
The unary minus when applied to an object should change
the sign of each of its data items.
10. Overloading Unary Operators
class space
{
int x, y, z;
public:
void getdata( int a, int b, int c);
void display(void);
void operator - (); // overload unary minus operator
};
11. Overloading Unary Operators
void space :: getdata(int a, int b, int c)
{
x = a;
y = b;
z = c;
}
void space :: display(void)
{
cout << x ;
cout << y ;
cout << z ;
}
12. Overloading Unary Operators
void space :: operator - ()
{
x = -x;
y = -y;
z = -z;
}
int main()
{
space S;
S.getdata(10, 20, 30);
S.display();
-S; // activates operator-() function
S.display();
return 0;
}
13. Practice Statement 1
Create a class date with day, month and year as its
members. Accept the date from the user and display it.
Overload the increment and decrement operators for
displaying the next and previous date for the given date.
14. Overloading Binary Operators
As a unary operator is overloaded we can also overload a binary
operator.
For e.g: A binary operator + can be overloaded to add two objects
rather than adding two variables.
Using operator overloading a functional notation,
C = sum(A, B);
Can be replaced by,
C = A + B;
18. Overloading binary operators using
Friends
Friend functions may be used in place of member functions
for overloading a binary operator.
A friend function requires two arguments to be explicitly
passed to it, while a member function requires only one.
For e.g:
complex operator + (complex);
friend complex operator + (complex, complex);
19. Overloading binary operators using
Friends
The operator function definition would also be modified as:
complex complex :: operator+(complex c)
{
complex temp;
temp.x = x + c.x;
temp.y = y + c.y;
return(temp);
}
complex operator + (complex a, complex b)
{
return complex((a.x + b.x), (a.y + b.y));
}
20. Overloading binary operators using
Friends
The statement,
C3 = C1 + C2;
Is equivalent to
C3 = operator+(C1, C2);
21. String Manipulations using friends
class string
{
char *p;
int len;
public:
string() { len = 0; p = 0;}
string( const char * s );
string ( const string & s );
~ string () { delete p; }
friend string operator+(const string & s , const string & t );
friend int operator<=(const string & s, const string & t );
friend void show( const string s);
};
22. String Manipulations using friends
string :: string ( const char * s)
{
len = strlen(s);
p = new char[len + 1];
strcpy(p, s);
}
string :: string (const string & s)
{
len = s. len;
p = new char[len+1];
strcpy(p, s.p);
}
27. Overloading Stream Insertion and
Extraction Operators
It is possible to overload the stream insertion (<<) and
extraction operators (>>) to work with classes.
This has advantages, in that
It makes programs more readable
It makes programs more extensible
It makes input and output more consistent
28. Overloading Stream Insertion and
Extraction Operators
istream & operator >> (istream &din, vector &b)
{
for (int i = 0; i < size; i++)
{
din>>b.v[i];
}
return(din);
}
29. Overloading Stream Insertion and
Extraction Operators
ostream & operator << (ostream &dout, rational &b)
{
dout<<“(“;
for (int i = 0; i < size; i++)
{
din>>b.v[i];
}
dout << “)”;
return(dout);
}
30. Practice Statement 2
Create a class rational to accept a rational number.
Perform all the arithmetic operations on rational
numbers by overloading all arithmetic operators ( +, - ,
* , / ). Also overload >> and << operators for taking
rational numbers as input and display them.
31. Type Conversion
Type conversion is a process of converting one data type to
another.
Type conversion is done automatically for the built-in
datatypes by the compiler.
Example:
int m;
float x = 3.14159;
m = x;
The above statements convert x to an integer before
assigning it to m.
For user defined data type the compiler has to be provided
with the type conversion function.
32. Type Conversion
There are three situations that arise when performing data
type conversion between incompatible types:
Conversion from basic type to class type
Conversion from class type to basic type
Conversion from one class type to another class type
33. Basic type to Class type
The conversion from basic type to class type is easily accomplish
by the use of constructors.
Constructors are used to initialize the objects and we can use
them to build a class type object from an basic type.
For example we can create a vector object from an int type array.
The constructors perform a defacto type conversion from the
argument’s type to the constructor’s class type.
The constructors used for the type conversion take a single
argument whose type is to be converted.
34. Basic type to class type (Example)
class time
{
int hrs;
int mins;
public:
time (int t) // constructor
{
hrs = t/60; // t in minutes
mins = t%60;
}
};
The following conversion statements can be used in a function:
time t1; // object t1 created
int duration = 85;
t1 = duration; // int to class type
35. Class type to Basic type
C++ allows an overloaded casting operator that could be
used to convert a class type data to a basic type.
General syntax:
Operator typename()
{
...........
...........
}
This function converts a class type data to typename.
For example, the operator double() converts a class
object to type double.
36. Class type to Basic type (Example)
Vector :: operator double()
{
double sum = 0;
for(int i =0; i<size; i++)
{
sum = sum + v[i] * v[i];
return sqrt(sum);
}
}
This function converts a vector to the corresponding scalar
magnitude.
The operator double() can be used as
double length = double(v1); OR
double length = v1;
37. Class type to Basic type
The casting operator function should satisfy the following
conditions:
It must be a class member.
It must not specify a return type.
It must not have any arguments.
38. One class to Another class type
Conversions between objects of different classes can be
carried out by either a constructor or a conversion function.
Consider the statement:
objX = objY;
The class Y type data is converted to the class X type data and
the converted value is assigned to the objX.
The class Y is known as source class and class X is known
as destination class.
39. One class to Another class type
When to use constructor and type conversion function?
40. One class to Another class type
(Example)
Consider an example of an inventory of products in store.
One way of recording the details of the product is to record
their code number, total items in the stock and the cost of
each item.
Another approach is to just specify the item code and the
value of the item in the stock.
Example.
42. Summary
State whetherTrue or False:
Using the operator overloading concept, we can change the
meaning of an operator.
Friend functions cannot be used to overload operators.
When using an overloaded binary operator, the left operand is
implicitly passed to the member function.
The overloaded operator must have atleast one operand that is
user-defined type.
Operator functions never return a value.
Through operator overloading, a class type data can be converted
to a basic type.
A constructor can be used to convert a basic type to a class type
data.
43. Short Answer Questions
Why is it necessary to overload and operator?
Operator overloading allows us to provide new implementations
for existing operators. Using operator overloading one can perform
the operation on the user defined data types in the same way as that
of built-in data types.
Example: Two integer values can be added as c = a + b. With the
use of operator overloading the + operator can also be used to
perform addition of two complex numbers as:
C3 = C1 + C2 where C1, C2 and C3 are the objects of class
complex.
44. Short Answer Questions
When is a friend function compulsory? Give example.
Friend function is used in a situation where we need to use two
different types of operands for a binary operator. One an object and
another a built-in data type.
A = 2 + B
Here the statement will not be executed by the member functions
as the left hand operand which is responsible for invoking the
member function is not the object of the same class. However the
friend function allows the statement to be executed.
45. Short Answer Questions
A friend function cannot be used to overload the
assignment operator = . Explain why?
In the assignment operator, the right hand operand is source and
lefthand operand is the target of assignment. When we overload
assignment operator as member function then the Lvalue becomes
the object for which the assignment operator is called and the Rvalue
object is passed as parameter. If the Rvalue is constant then by using
the constructor that value can be converted into object and then will
be passed as parameter to the assignment operator. But in case of
friend function both the Lvalue and Rvalue needs to be passed as
parameter. If the Lvalue is constant then it gets converted into the
class object by constructor which results in changing the constant
value which is not allowed/illegal. Hence, to avoid modifying
constant as Lvalue assignment operator was restricted to be
overloaded as friend function.
46. Short Answer Questions
Name the operators that cannot be overloaded.
Class member access operators (., .*)
Scope resolution operator (::)
Size operator (sizeof )
Conditional operator (?:)
Name the operators that cannot be overloaded
using friend function.
Assignment operator ( = )
Function call operator ( )
Subscripting operator [ ]
Class member access operator ( -> )
47. Short Answer Questions
What is conversion function. How is it created.
Explain its syntax.
The conversion function is the overloaded casting operator
that is used to convert a class type data to basic type data.
Syntax:
Operator typename()
{
...........
...........
}
This function converts a class type data to typename.
Operator int() converts a class type object to type int.
48. Short Answer Questions
A class alpha has a constructor as follows:
Alpha ( int a, double b);
Can we use this constructor to convert types?
No, we cannot use this constructor to convert types because
when the constructors are used for the type conversion it take a
single argument whose type is to be converted.
In the given example the alpha constructor is having two
arguments int and double.
49. Short Answer Questions
We have two classes X and Y. If a is an object of X
and b is an object of Y and we want to say a = b;
what type of conversion routine should be used and
where?
To perform the conversion a = b we use the type casting
operator function in the source class. The conversion takes place
in theY class and the result is given to the X class.