LAB 05
Summary
Items Description
Course Title Object Oriented Programming
Lab Title Operator Overloading
Duration 3 Hours
Operating Visual Studio
System
/Tool/Language
Objective To understand the concept of operator
overloading and its syntax and, overload
arithmetic unary and binary operators
C++ incorporates the option to use standard operators to perform operations with
classes in addition to with fundamental types. For example:
int a, b,
c; a = b
+ c;
This is valid code in C++, since the different variables of the addition are all fundamental
types. Nevertheless, it is not so obvious that we could perform an operation similar to the
following one:
struct {
string
product; float
price;
} a, b, c;
a = b + c;
In fact, this will cause a compilation error, since we have not defined the behavior our
class should have with addition operations. However, as a result of the C++ feature to
overload operators, we can design classes able to perform operations using standard
operators. Here is a list of all the operators that can be overloaded:
Overloadable operators
+ - * / = < > += -= *= /= << >> <<= >>= == != <=
>= ++ -- % & ^ ! | ~ &= ^= |= && || %= [] () , ->* ->
new delete new[] delete[]
To overload an operator in order to use it with classes we declare operator functions,
which are regular functions whose names are the operator keyword followed by the
operator sign that we want to overload. The format is:
type operator sign (parameters) { /*...*/ }
Overloading Unary Operators
We will first have a look at how to overload the unary operators. As an example, we will
be overloading the increment (++) and decrement (--) operators. Overloading the
increment (++) and decrement (--) operators are pretty straightforward, with one small
exception. There are actually two versions of the increment and decrement operators: a
prefix increment and decrement (eg.++nX; --nY;) and a postfix increment and decrement
(eg. nX++; nY--;).
Because the increment and decrement operators modify their operands, they’re best
overloaded as member functions. We’ll tackle the prefix versions first because they’re
the most straightforward.
Example 5.1
// vectors: overloading operators example
#include <iostream>
using namespace std;
class counter
{
private:
int count;
public:
counter():count(0){}
counter(int c):count(c) {}
int get_count()
{
return count;
}
counter operator++ ()
{
return counter(++count);
}
counter operator-- ()
{
return counter(--count);
}
};
int main()
{
counter c1, c2, c3;
++c1;
++c2;
cout<<'\n'<<c1.get_count();
cout<<'\n'<<c2.get_count();
cout<<endl;
c3 = --c1;
cout<<'\n'<<c3.get_count();
return 0;
}
Output:
1
1
0
Normally, functions can be overloaded when they have the same name but a different
number and/or different type of parameters. However, consider the case of the prefix
and postfix increment and decrement operators. Both have the same name (eg.
operator++),
are unary, and take one parameter of the same type. So how it is possible to
differentiate the two when overloading?
The answer is that C++ uses a “dummy variable” or “dummy argument” for the postfix
operators. This argument is a fake integer parameter that only serves to distinguish the
postfix version of increment/decrement from the prefix version.
Example 5.2
// vectors: overloading operators example
#include <iostream>
using namespace std;
class counter
{
private:
int count;
public:
counter():count(0){}
counter(int c):count(c) {}
int get_count()
{
return count;
}
counter operator++ (int)
{
return counter(count++);
}
counter operator-- (int)
{
return counter(count--);
}
};
int main()
{
counter c1, c2, c3;
c1++;
c2--;
cout<<'\n'<<c1.get_count();
cout<<'\n'<<c2.get_count();
cout<<endl;
c3 = c1++;
cout<<'\n'<<c1.get_count();
cout<<'\n'<<c3.get_count();
getch();
return 0;
}
Output:
1
-1
2
1
Overloading Binary Operators
Some of the most commonly used operators in C++ are the arithmetic operators — that
is, the plus operator (+), minus operator (-), multiplication operator (*), and division
operator (/). Note that all of the arithmetic operators are binary operators — meaning
they take two operands — one on each side of the operator. All four of these operators
are overloaded in the exact same way.
Following is an example that overloads the addition operator (+). We are going to create
a class to store two dimensional vectors and then we are going to add two of them:
a(3,1) and b(1,2). The addition of two bi-dimensional vectors is an operation as simple
as adding the two x coordinates to obtain the resulting x coordinate and adding the two
y coordinates to obtain the resulting y. In this case the result will be (3+1,1+2) = (4,3).
Example 5.3
// vectors: overloading operators example
#include <iostream>
using namespace std;
class CVector {
public:
int x,y;
CVector () {};
CVector (int,int);
CVector operator + (CVector);
};
CVector::CVector (int a, int b) {
x = a;
y = b;
}
CVector CVector::operator+ (CVector param) {
CVector temp;
temp.x = x + param.x;
temp.y = y + param.y;
return temp;
}
int main () {
CVector a (3,1);
CVector b (1,2);
CVector c;
c = a + b;
cout << c.x << "," << c.y;
return 0;
}
Output:
4,3
The function operator+ of class CVector is the one that is in charge of overloading the
addition operator (+). This function can be called either implicitly using the operator, or
explicitly using the function name:
c = a + b;
c = a.operator+
(b);
Both expressions are equivalent.
Notice also that we have included the empty constructor (without parameters) and we
have defined it with an empty block:
CVector () {
};
This is necessary, since we have explicitly declared another constructor:
CVector (int,
int);
And when we explicitly declare any constructor, with any number of parameters, the
default constructor with no parameters that the compiler can declare automatically is not
declared, so we need to declare it ourselves in order to be able to construct objects of
this type without parameters. Otherwise, the declaration:
CVector
c;
included in main() would not have been valid.
++++++++++++++
LAB TASK
Task #01
1. What is operator overloading?
2. Is it possible to overload the ‘+’ operator for data type int?
3. How do we differentiate between prefix and postfix increment operator while
overloading them?
4. What is the syntax of overlading ‘*’ operator for a class Matrix. (You do not need to
write the body of the function)
5. Go through example 5.2 of the manual and write the output of the given code segment.
counter c1(5), c2(10), c3;
c3=c1++;
c2=--c3;;
cout<<'\n'<<c1.get_count();
cout<<'\n'<<c2.get_count();
cout<<'\n'<<c3.get_count();
TASK # 02
Write a complete C++ program with the following features.
a. Declare a class Time with two fields hour and minute.
b. Provide appropriate constructors to initialize the data members. c. Overload the
pre and postfix increment operators to increment the minutes by one . Also make
sure if minutes are 59 and you increment the Time it should update hours and
minutes accordingly.
d. Provide a function display() to display the hours and minutes. e. In main(), create
two objects of Time, initialize them using constructors and call the display functions.
f. Test the following in your main:
a. T3= ++T1;
b. T4=T2++;
Task#03
Implement above taks in sepearte header file and cpp file