You are on page 1of 21

Object oriented Programming

Lecture 8: Operator overloading

Object oriented programming in C++ by Robert Lafore 1


Recap..
• Static and const attributes and functions
• Array of pointers
• Pointers to objects
• This pointer
• Array of pointers to objects
• Cascading function calls

Object oriented programming in C++ by Robert Lafore 2


Recommended reads
Object oriented programming in C++ by Robert Lafore: Chapter 8: Operator
Overloading

Object oriented programming in C++ by Robert Lafore 3


Copy constructor [Revisiting]
• C++ compiler provide default copy constructor (and assignment operator) with class.
• When we don’t provide implementation of copy constructor, default copy constructor
gets called
• It works well with non-dynamic attributes
• Problems:
• When we have members which dynamically gets initialized at run time, default copy
constructor copies this members with address of dynamically allocated memory and not
real copy of this memory.
• Now both the objects points to the same memory and changes in one reflects in another
object
• Further, when we delete one of this object other object still points to same memory,
which will be dangling pointer
• in such cases, we should always write our own copy constructor

Object oriented programming in C++ by Robert Lafore 4


ClassName (const ClassName &old_obj);

class Point int main()


{ {
private: Point p1(10, 15); // Normal constructor is called here
int x, y; Point p2 = p1; // Copy constructor is called here
public: }
Point(int x1, int y1) { x = x1; y = y1; }

// Copy constructor
Point(const Point &p2) {x = p2.x; y = p2.y; }

int getX() { return x; }


int getY() { return y; }
};

Object oriented programming in C++ by Robert Lafore 5


• Default constructor does only shallow copy
• Deep copy is possible only with user defined copy constructor. In user defined
copy constructor, we make sure that pointers (or references) of copied object
point to new memory locations.
• Copy constructor vs Assignment Operator
• MyClass t1, t2;
• MyClass t3 = t1; // ----> (1)
• t2 = t1; // -----> (2)
• Copy constructor is called when a new object is created from an existing object,
as a copy of the existing object.
• Assignment operator is called when an already initialized object is assigned a new
value from another existing object.
• In the above example (1) calls copy constructor and (2) calls assignment operator.

Object oriented programming in C++ by Robert Lafore 6


Default assignment operator= in c++ is a shallow copy
class Test
{
public: int main()
Test() {} {
Test(const Test &t) Test t1, t2;
{ t2 = t1; //Default Assignment operator
cout<<"Copy constructor called "<<endl; Test t3 = t1; //copy constructor
} return 0;
}
Test& operator = (const Test &t)
{
cout<<"Assignment operator called "<<endl;
return *this; t2 = t1; // calls assignment operator, same as "t2.operator=(t1);"
} Test t3 = t1; // calls copy constructor, same as "Test t3(t1);"
};

Object oriented programming in C++ by Robert Lafore 7


Shallow copy
Class Dummy
public: int main()
Int *x; {
Dummy(int m) Dummy d1(4);
{ Dummy d2 = d1; //Copy constructor
x = new int; d1.display();
*x = m; d2.display();
}
d1.set(10);
int get() const
{
d1.display();
return *x; d2.display();
} return 0;
void set(int m) }
{
*x = m;
}
void display()
{
cout << “Value of ptr : " << *x << endl;
cout << “Address of ptr : " << x << endl;
}
};
Object oriented programming in C++ by Robert Lafore 8
Deep copy
Class Dummy
public: int main()
Int *x; {
Dummy(int m) Dummy(const Dummy &obj) Dummy d1(4);
{ { Dummy d2 = d1; //Copy constructor
x = new int; x = new int; d1.display();
*x = m; *x = obj.get(); d2.display();
} } d1.set(10);
int get() const
{
d1.display();
return *x; d2.display();
} return 0;
void set(int m) }
{
*x = m;
}
void display()
{
cout << “Value of ptr : " << *x << endl;
cout << “Address of ptr : " << x << endl;
}
};
Object oriented programming in C++ by Robert Lafore 9
Operator overloading
• statements like d3.addobjects(d1, d2); Or d3 = d1.addobjects(d2);
can be changed to the much more readable d3 = d1 + d2;
• normal C++ operators works for basic data types such as int, double, char..
a=b+c
• Using overloading, you can make this statement legal even when a, b, and c are
user-defined types.
• Overloaded function with operator keyword: void operator ++ ()

Object oriented programming in C++ by Robert Lafore 10


Overloading Unary Operators
• increment and decrement operators ++ and –

Object oriented programming in C++ by Robert Lafore 11


Prefix increment: ++object

class Counter int main()


{ {
private: Counter c1, c2; //define and initialize
unsigned int count; //count cout << “\nc1=” << c1.get_count(); //display
public: cout << “\nc2=” << c2.get_count();
Counter() : count(0) //constructor ++c1; //increment c1
{} ++c2; //increment c2
unsigned int get_count() //return count ++c2; //increment c2
{ return count; } cout << “\nc1=” << c1.get_count(); //display again
void operator ++ () //increment (prefix) cout << “\nc2=” << c2.get_count() << endl;
{ return 0;
++count; }
}
};

Object oriented programming in C++ by Robert Lafore 12


Counter operator ++ () //increment count int main()
{ {
++count; //increment count Counter c1, c2; //c1=0, c2=0
Counter temp; //make a temporary Counter cout << “\nc1=” << c1.get_count(); //display
temp.count = count; //give it same value as this obj cout << “\nc2=” << c2.get_count();
return temp; //return the copy c2 = ++c1; //c1=1, c2=1
} }

Object oriented programming in C++ by Robert Lafore 13


Nameless Temporary Objects
class Counter Counter temp;
{ temp.count = count;
private: return temp;
unsigned int count; //count
public: int main()
Counter() : count(0) //constructor no args {
{} Counter c1, c2; //c1=0, c2=0
Counter(int c) : count(c) //constructor, one arg cout << “\nc1=” << c1.get_count(); //display
{} cout << “\nc2=” << c2.get_count();
unsigned int get_count() //return count c2 = ++c1; //c1=2, c2=2
{ return count; } }
Counter operator ++ () //increment count
{
++count; // increment count, then return
return Counter(count); // an unnamed temporary
object
} // initialized to this count
};
Object oriented programming in C++ by Robert Lafore 14
Using parametrized constructor inside overloaded function
class Counter Counter temp;
{ temp.count = count;
private: return temp;
unsigned int count; //count
public: int main()
Counter() : count(0) //constructor no args {
{} Counter c1, c2; //c1=0, c2=0
Counter(int c) : count(c) //constructor, one arg cout << “\nc1=” << c1.get_count(); //display
{} cout << “\nc2=” << c2.get_count();
unsigned int get_count() //return count c2 = ++c1; //c1=2, c2=2
{ return count; } }
Counter operator ++ () //increment count (prefix)
{
return Counter(++count); //an unnamed temporary
object
}
};
Object oriented programming in C++ by Robert Lafore 15
Postfix increment: object++

class Counter int main()


{ {
private: Counter c1, c2; //define and initialize
unsigned int count; //count cout << “\nc1=” << c1.get_count(); //display
public: cout << “\nc2=” << c2.get_count();
Counter() : count(0) //constructor c2 = c1++;
{} cout << “\nc1=” << c1.get_count(); //display again
Counter(int c) : count(c) //constructor, one arg cout << “\nc2=” << c2.get_count() << endl;
{} return 0;
unsigned int get_count() //return count }
{ return count; }
Counter operator ++ (int) //increment count (postfix)
{
return Counter(count++); OR
} c2 = c1.operator++;
};
Object oriented programming in C++ by Robert Lafore 16
Overloading Binary Operators
dist3.add_dist(dist1, dist2);
• By overloading the + operator we can reduce this dense-looking expression to
dist3 = dist1 + dist2;
OR
dist3 = dist1.operator+(dist2);

Object oriented programming in C++ by Robert Lafore 17


Distance Distance::operator + (Distance d2) //return sum
{ Main():
int f = feet + d2.feet; //add the feet
float i = inches + d2.inches; //add the inches Distance dist1, dist3, dist4; //define distances
return Distance(f,i); dist1.getdist(); //get dist1 from user
} Distance dist2(11, 6.25); //define, initialize dist2
dist3 = dist1 + dist2;

Object oriented programming in C++ by Robert Lafore 18


Concatenating strings
String operator + (String ss) const //add Strings
• str3 = str1 + str2; {
String temp; //make a temporary String
class String //user-defined string type strcpy(temp.str, str); //copy this string to temp
{ strcat(temp.str, ss.str); //add the argument string
private: return temp; //return temp String
char str[80]; //holds a string }
public: };
String() Main()
{ strcpy(str, “”); }
String( char s[] ) String s1 = “\nMerry Christmas! “; //uses constructor 2
{ strcpy(str, s); } String s2 = “Happy new year!”; //uses constructor 2
void display() const String s3;
{ cout << str; }
s3 = s1 + s2; //add s2 to s1,
s3.display();

Object oriented programming in C++ by Robert Lafore 19


Arithmetic Assignment Operators

void Distance::operator += (Distance d2)


{ dist1 += dist2; //dist1 = dist1 + dist2
feet += d2.feet; //add the feet
inches += d2.inches; //add the inches
}

Object oriented programming in C++ by Robert Lafore 20


That’s it

Object oriented programming in C++ by Robert Lafore 21

You might also like