11. Operator Overloading (1)
11. Operator Overloading (1)
• Coding Example:
Comparison between
Copy Constructor
and Assignment
Operator
The main purpose of both the
concepts in C++ is to assign the
value, but the main difference
between both is copy
constructor creates a new object
and assigns the value but
assignment operator does not
create a new object, instead it
assigns the value to the data
member of the same object.
The following table highlights
the major differences between
copy constructor and assignment
operator.
Conclusion
• The difference between a copy constructor and an assignment
operator is that a copy constructor helps to create a copy of an
already existing object without altering the original value of the
created object, whereas an assignment operator helps to assign a
new value to a data member or an object in the program.
Operator Functions as
Class Members vs. as friend
Functions
• Member vs non-member
• Operator functions can be member or non-member functions
• When overloading ( ), [ ], -> or any of the assignment
operators, must use a member function
• Operator functions as member functions
• Leftmost operand must be an object (or reference to an
object) of the class
• If left operand of a different type, operator function must be a non-
member function
• Operator functions as non-member functions
• Must be friends if needs to access private or protected
members
• Enable the operator to be commutative
Overloading stream insertion
(<>) operators
• In C++, stream insertion operator “<<” is used for output and
extraction operator “>>” is used for input.
• We must know the following things before we start overloading these
operators.
1) cout is an object of ostream class and cin is an object of istream
class
2) These operators must be overloaded as a global function. And if we
want to allow them to access private data members of the class, we
must make them friend.
Why these operators must be overloaded as
global?
class Complex
{ int main()
private: {
int real, imag; Complex c1;
public:
Complex(int r = 0, int i =0)
cin >> c1;
{ real = r; imag = i; } cout << "The complex object is ";
friend ostream & operator << (ostream &out, const Complex &c); cout << c1;
friend istream & operator >> (istream &in, Complex &c); return 0;
}; }
ostream & operator << (ostream &out, const Complex &c)
{
out << c.real;
out << "+i" << c.imag << endl;
return out;
}