SlideShare a Scribd company logo
Operator Overloading
Customised behaviour of operators
Unit - III
Unit Introduction
This unit covers operator overloading
Unit Objectives
After covering this unit you will understand…
 Operator overloading
 Different types of operator and their
overloading
 Operators that cannot be overloaded
 Inheritance and overloading
 Automatic type conversion
4
Introduction
 Operator overloading
 Enabling C++’s operators to work with class
objects
 Using traditional operators with user-defined
objects
 Requires great care; when overloading is misused,
program difficult to understand
 Examples of already overloaded operators
 Operator << is both the stream-insertion operator and
the bitwise left-shift operator
 + and -, perform arithmetic on multiple types
 Compiler generates the appropriate code based on
the manner in which the operator is used
5
 Overloading an operator
 Write function definition as normal
 Function name is keyword operator followed by
the symbol for the operator being overloaded
 operator+ used to overload the addition
operator (+)
 Using operators
 To use an operator on a class object it must be
overloaded unless the assignment operator(=)or
the address operator(&)
 Assignment operator by default performs memberwise
assignment
 Address operator (&) by default returns the address of an
object
6
Restrictions on Operator Overloading
 ++ operators that can be overloaded
 C++ Operators that cannot be overloaded
Operators that cannot be overloaded
. .* :: ?: sizeof
COperators that can be overloaded
+ - * / % ^ & |
~ ! = < > += -= *=
/= %= ^= &= |= << >> >>=
<<= == != <= >= && || ++
-- ->* , -> [] () new delete
new[] delete[]
7
Restrictions on Operator Overloading
 Overloading restrictions
 Precedence of an operator cannot be changed
 Associativity 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
Operator Functions as Class
Members vs. as friend Functions Member vs non-member
 In general, 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
8
9
Overloading Stream-Insertion and Stream-Extraction
Operators
 Overloaded << and >> operators
 Overloaded to perform input/output for user-
defined types
 Left operand of types ostream & and istream
&
 Must be a non-member function because left
operand is not an object of the class
 Must be a friend function to access private data
members
10
Overloading Unary Operators
 Overloading unary operators
 Can be overloaded with no arguments or one
argument
 Should usually be implemented as member functions
 Avoid friend functions and classes because they
violate the encapsulation of a class
 Example declaration as a member function:
class String {
public:
bool operator!() const;
...
};
11
Overloading Unary Operators
 Example declaration as a non-member function
class String {
friend bool operator!( const
String & )
...
}
12
Overloading Binary Operators
 Overloaded Binary operators
 Non-static member function, one argument
 Example:
class Complex {
public:
const Complex operator+ (
const Complex &);
...
};
13
Overloading Binary Operators
 Non-member function, two arguments
 Example:
class Complex {
friend Complex operator +(
const Complex &, const Complex &
);
...
};
Example: Operator Overloading
class OverloadingExample
{
private:
int m_LocalInt;
public:
OverloadingExample(int j) // default constructor
{
m_LocalInt = j;
}
int operator+ (int j) // overloaded + operator
{
return (m_LocalInt + j);
}
};
Example: Operator Overloading (contd.)
void main()
{
OverloadingExample object1(10);
cout << object1 + 10; // overloaded operator called
}
Types of Operator
 Unary operator
 Binary operator
Unary Operators
 Operators attached to a single operand (-a, +a, --
a, a--, ++a, a++)
Example: Unary Operators
class UnaryExample
{
private:
int m_LocalInt;
public:
UnaryExample(int j)
{
m_LocalInt = j;
}
int operator++ ()
{
return (m_LocalInt++);
}
};
Example: Unary Operators (contd.)
void main()
{
UnaryExample object1(10);
cout << object1++; // overloaded operator results in value
// 11
}
Unary Overloaded Operators -- Member Functions
 Invocation in Two Ways-- Object@(Direct) or Object.operator@()(As a
Function)
class number{
int n;
public:
number(int x = 0):n(x){};
number operator-(){return number (-n);}
};
main()
{
number a(1), b(2), c, d;
//Invocation of "-" Operator -- direct
d = -b; //d.n = -2
//Invocation of "-" Operator -- Function
c = a.operator-(); //c.n = -1
}
20
21
Binary Overloaded Operators -- Member Functions
 Invocation in Two Ways-- ObjectA@ ObjectB(direct) or
ObjectA.operator@(ObjectB)(As a Function)
class number{
int n;
public:
number(int x = 0):n(x){};
number operator+(number ip)
{return number (ip.n + n);}
};
main()
{
number a(1), b(2), c, d;
//Invocation of "+" Operator -- direct
d = a + b; //d.n = 3
//Invocation of "+" Operator -- Function
c = d.operator+(b); //c.n = d.n + b.n = 5
}
Binary Operators
 Operators attached to two operands (a-b, a+b,
a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b)
Example: Binary Operators
class BinaryExample
{
private:
int m_LocalInt;
public:
BinaryExample(int j)
{
m_LocalInt = j;
}
int operator+ (BinaryExample& rhsObj)
{
return (m_LocalInt + rhsObj.m_LocalInt);
}
};
Example: Binary Operators (contd.)
void main()
{
BinaryExample object1(10), object2(20);
cout << object1 + object2; // overloaded operator called
}
Non-Overloadable Operators
 Operators that can not be overloaded due to
safety reasons:
 Member Selection ‘.’operator
 Member dereference ‘.*’operator
 Exponential ‘**’operator
 User-defined operators
 Operator precedence rules
Operator Overloading and Inheritance
 An operator is overloaded in super class but
not overloaded in derived class is called non-
member operator in derived class
 In above, if operator is also overloaded in
derived class it is called member-operator
 = ( ) []–> –>* operators must be member
operators
 Other operators can be non-member
operators
Automatic Type Conversion
 Automatic type conversion by the C++
compiler from the type that doesn’t fit, to the
type it wants
 Two types of conversion:
 Constructor conversion
 Operator conversion
Constructor Conversion
 Constructor having a single argument of another
type, results in automatic type conversion by the
compiler
 Prevention of constructor type conversion by
use of explicit keyword
Example: Constructor Conversion
class One
{
public:
One() {}
};
class Two
{
public:
Two(const One&) {}
};
void f(Two) {}
void main()
{
One one;
f(one); // Wants a Two, has a One
}
Operator Conversion
 Create a member function that takes the current
type
 Converts it to the desired type using the
operator keyword followed by the type you
want to convert to
 Return type is the name of the operator
overloaded
 Reflexivity - global overloading instead of
member overloading; for code saving
Example: Operator Conversion
class Three
{
int m_Data;
public:
Three(int ii = 0, int = 0) : m_Data(ii) {}
};
class Four
{
int m_Data;
public:
Four(int x) : m_Data(x) {}
operator Three() const
{
return Three(m_Data);
}
};
void g(Three) {}
Example: Operator Conversion (contd.)
void main()
{
Four four(1);
g(four);
g(1); // Calls Three(1,0)
}
Type Conversion Pitfalls
 Compiler performs automatic type conversion
independently, therefore it may have the
following pitfalls:
 Ambiguity with two classes of same type
 Automatic conversion to more than one type - fan-
out
 Adds hidden activities (copy-constructor etc)
Unit Summary
In this unit you have covered …
 Operator overloading
 Different types of operator
 Operators that cannot be overloaded
 Inheritance and overloading
 Automatic type conversion

More Related Content

PPTX
Operator overloading
PPT
Operator overloading
PPTX
Operator overloadng
PDF
Operator overloading
PPTX
Operator overloading
PPTX
OPERATOR OVERLOADING IN C++
PPT
Operator overloading
PPT
Lec 26.27-operator overloading
Operator overloading
Operator overloading
Operator overloadng
Operator overloading
Operator overloading
OPERATOR OVERLOADING IN C++
Operator overloading
Lec 26.27-operator overloading

What's hot (20)

PPTX
PPT
08 c++ Operator Overloading.ppt
PPT
C++ overloading
PPTX
Operator overloading
PPTX
Operator overloading and type conversion in cpp
PPTX
Operator Overloading and Scope of Variable
PPT
14 operator overloading
PPTX
Operator overloading and type conversions
PPTX
Bca 2nd sem u-4 operator overloading
PPTX
Presentation on overloading
PPT
Operator Overloading
PPTX
operator overloading & type conversion in cpp over view || c++
PPTX
operator overloading
PPT
Lec 28 - operator overloading
PPTX
Unary operator overloading
PPT
Operator overloading
PPTX
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
PPT
C cpluplus 2
PPTX
08 c++ Operator Overloading.ppt
C++ overloading
Operator overloading
Operator overloading and type conversion in cpp
Operator Overloading and Scope of Variable
14 operator overloading
Operator overloading and type conversions
Bca 2nd sem u-4 operator overloading
Presentation on overloading
Operator Overloading
operator overloading & type conversion in cpp over view || c++
operator overloading
Lec 28 - operator overloading
Unary operator overloading
Operator overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
C cpluplus 2
Ad

Similar to Operator overloaing (20)

PDF
Ch-4-Operator Overloading.pdf
PDF
Lec 8.pdf a
PDF
OOPS-Seminar.pdf
PPTX
Operator Overloading
PPTX
Cpp (C++)
PDF
NIKUL SURANI
PPT
Polymorphism and function overloading_new.ppt
PDF
Operator_Overloaing_Type_Conversion_OOPC(C++)
PPTX
Operator overloading (binary)
PDF
Object Oriented Programming using C++ - Part 3
PDF
Operator Overloading in C++
PPT
3d7b7 session4 c++
PDF
OOP_UnitIII.pdf
PPT
Overloading
PPT
08 c-operator-overloadingppt2563
PPTX
Mca 2nd sem u-4 operator overloading
PPT
Synapse india complain sharing info on chapter 8 operator overloading
PDF
Operator overloading C++
PPT
Unary operator overloading
PPTX
Operator overloading
Ch-4-Operator Overloading.pdf
Lec 8.pdf a
OOPS-Seminar.pdf
Operator Overloading
Cpp (C++)
NIKUL SURANI
Polymorphism and function overloading_new.ppt
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator overloading (binary)
Object Oriented Programming using C++ - Part 3
Operator Overloading in C++
3d7b7 session4 c++
OOP_UnitIII.pdf
Overloading
08 c-operator-overloadingppt2563
Mca 2nd sem u-4 operator overloading
Synapse india complain sharing info on chapter 8 operator overloading
Operator overloading C++
Unary operator overloading
Operator overloading
Ad

More from zindadili (20)

PPTX
Namespaces
PPTX
Namespace1
PPTX
Exception handling
PPT
Exception handling
PPTX
Templates2
PPTX
Templates1
PPTX
Virtual function
PPTX
Operator overloading2
PPTX
Polymorphism
PPTX
Function overloading
PPTX
Aggregation
PPTX
Hierarchical inheritance
PPTX
Hybrid inheritance
PPTX
Multiple inheritance
PPTX
Abstraction1
PPTX
Abstraction
PPTX
Access specifier
PPTX
Inheritance
PPTX
Friend function
PPTX
Enum
Namespaces
Namespace1
Exception handling
Exception handling
Templates2
Templates1
Virtual function
Operator overloading2
Polymorphism
Function overloading
Aggregation
Hierarchical inheritance
Hybrid inheritance
Multiple inheritance
Abstraction1
Abstraction
Access specifier
Inheritance
Friend function
Enum

Recently uploaded (20)

PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Institutional Correction lecture only . . .
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PDF
Microbial disease of the cardiovascular and lymphatic systems
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
PDF
01-Introduction-to-Information-Management.pdf
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Pharma ospi slides which help in ospi learning
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
Pre independence Education in Inndia.pdf
Microbial diseases, their pathogenesis and prophylaxis
Institutional Correction lecture only . . .
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Week 4 Term 3 Study Techniques revisited.pptx
Microbial disease of the cardiovascular and lymphatic systems
102 student loan defaulters named and shamed – Is someone you know on the list?
The Healthy Child – Unit II | Child Health Nursing I | B.Sc Nursing 5th Semester
01-Introduction-to-Information-Management.pdf
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Pharma ospi slides which help in ospi learning
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
O5-L3 Freight Transport Ops (International) V1.pdf
Anesthesia in Laparoscopic Surgery in India
Pre independence Education in Inndia.pdf

Operator overloaing

  • 2. Unit Introduction This unit covers operator overloading
  • 3. Unit Objectives After covering this unit you will understand…  Operator overloading  Different types of operator and their overloading  Operators that cannot be overloaded  Inheritance and overloading  Automatic type conversion
  • 4. 4 Introduction  Operator overloading  Enabling C++’s operators to work with class objects  Using traditional operators with user-defined objects  Requires great care; when overloading is misused, program difficult to understand  Examples of already overloaded operators  Operator << is both the stream-insertion operator and the bitwise left-shift operator  + and -, perform arithmetic on multiple types  Compiler generates the appropriate code based on the manner in which the operator is used
  • 5. 5  Overloading an operator  Write function definition as normal  Function name is keyword operator followed by the symbol for the operator being overloaded  operator+ used to overload the addition operator (+)  Using operators  To use an operator on a class object it must be overloaded unless the assignment operator(=)or the address operator(&)  Assignment operator by default performs memberwise assignment  Address operator (&) by default returns the address of an object
  • 6. 6 Restrictions on Operator Overloading  ++ operators that can be overloaded  C++ Operators that cannot be overloaded Operators that cannot be overloaded . .* :: ?: sizeof COperators that can be overloaded + - * / % ^ & | ~ ! = < > += -= *= /= %= ^= &= |= << >> >>= <<= == != <= >= && || ++ -- ->* , -> [] () new delete new[] delete[]
  • 7. 7 Restrictions on Operator Overloading  Overloading restrictions  Precedence of an operator cannot be changed  Associativity 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
  • 8. Operator Functions as Class Members vs. as friend Functions Member vs non-member  In general, 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 8
  • 9. 9 Overloading Stream-Insertion and Stream-Extraction Operators  Overloaded << and >> operators  Overloaded to perform input/output for user- defined types  Left operand of types ostream & and istream &  Must be a non-member function because left operand is not an object of the class  Must be a friend function to access private data members
  • 10. 10 Overloading Unary Operators  Overloading unary operators  Can be overloaded with no arguments or one argument  Should usually be implemented as member functions  Avoid friend functions and classes because they violate the encapsulation of a class  Example declaration as a member function: class String { public: bool operator!() const; ... };
  • 11. 11 Overloading Unary Operators  Example declaration as a non-member function class String { friend bool operator!( const String & ) ... }
  • 12. 12 Overloading Binary Operators  Overloaded Binary operators  Non-static member function, one argument  Example: class Complex { public: const Complex operator+ ( const Complex &); ... };
  • 13. 13 Overloading Binary Operators  Non-member function, two arguments  Example: class Complex { friend Complex operator +( const Complex &, const Complex & ); ... };
  • 14. Example: Operator Overloading class OverloadingExample { private: int m_LocalInt; public: OverloadingExample(int j) // default constructor { m_LocalInt = j; } int operator+ (int j) // overloaded + operator { return (m_LocalInt + j); } };
  • 15. Example: Operator Overloading (contd.) void main() { OverloadingExample object1(10); cout << object1 + 10; // overloaded operator called }
  • 16. Types of Operator  Unary operator  Binary operator
  • 17. Unary Operators  Operators attached to a single operand (-a, +a, -- a, a--, ++a, a++)
  • 18. Example: Unary Operators class UnaryExample { private: int m_LocalInt; public: UnaryExample(int j) { m_LocalInt = j; } int operator++ () { return (m_LocalInt++); } };
  • 19. Example: Unary Operators (contd.) void main() { UnaryExample object1(10); cout << object1++; // overloaded operator results in value // 11 }
  • 20. Unary Overloaded Operators -- Member Functions  Invocation in Two Ways-- Object@(Direct) or Object.operator@()(As a Function) class number{ int n; public: number(int x = 0):n(x){}; number operator-(){return number (-n);} }; main() { number a(1), b(2), c, d; //Invocation of "-" Operator -- direct d = -b; //d.n = -2 //Invocation of "-" Operator -- Function c = a.operator-(); //c.n = -1 } 20
  • 21. 21 Binary Overloaded Operators -- Member Functions  Invocation in Two Ways-- ObjectA@ ObjectB(direct) or ObjectA.operator@(ObjectB)(As a Function) class number{ int n; public: number(int x = 0):n(x){}; number operator+(number ip) {return number (ip.n + n);} }; main() { number a(1), b(2), c, d; //Invocation of "+" Operator -- direct d = a + b; //d.n = 3 //Invocation of "+" Operator -- Function c = d.operator+(b); //c.n = d.n + b.n = 5 }
  • 22. Binary Operators  Operators attached to two operands (a-b, a+b, a*b, a/b, a%b, a>b, a>=b, a<b, a<=b, a==b)
  • 23. Example: Binary Operators class BinaryExample { private: int m_LocalInt; public: BinaryExample(int j) { m_LocalInt = j; } int operator+ (BinaryExample& rhsObj) { return (m_LocalInt + rhsObj.m_LocalInt); } };
  • 24. Example: Binary Operators (contd.) void main() { BinaryExample object1(10), object2(20); cout << object1 + object2; // overloaded operator called }
  • 25. Non-Overloadable Operators  Operators that can not be overloaded due to safety reasons:  Member Selection ‘.’operator  Member dereference ‘.*’operator  Exponential ‘**’operator  User-defined operators  Operator precedence rules
  • 26. Operator Overloading and Inheritance  An operator is overloaded in super class but not overloaded in derived class is called non- member operator in derived class  In above, if operator is also overloaded in derived class it is called member-operator  = ( ) []–> –>* operators must be member operators  Other operators can be non-member operators
  • 27. Automatic Type Conversion  Automatic type conversion by the C++ compiler from the type that doesn’t fit, to the type it wants  Two types of conversion:  Constructor conversion  Operator conversion
  • 28. Constructor Conversion  Constructor having a single argument of another type, results in automatic type conversion by the compiler  Prevention of constructor type conversion by use of explicit keyword
  • 29. Example: Constructor Conversion class One { public: One() {} }; class Two { public: Two(const One&) {} }; void f(Two) {} void main() { One one; f(one); // Wants a Two, has a One }
  • 30. Operator Conversion  Create a member function that takes the current type  Converts it to the desired type using the operator keyword followed by the type you want to convert to  Return type is the name of the operator overloaded  Reflexivity - global overloading instead of member overloading; for code saving
  • 31. Example: Operator Conversion class Three { int m_Data; public: Three(int ii = 0, int = 0) : m_Data(ii) {} }; class Four { int m_Data; public: Four(int x) : m_Data(x) {} operator Three() const { return Three(m_Data); } }; void g(Three) {}
  • 32. Example: Operator Conversion (contd.) void main() { Four four(1); g(four); g(1); // Calls Three(1,0) }
  • 33. Type Conversion Pitfalls  Compiler performs automatic type conversion independently, therefore it may have the following pitfalls:  Ambiguity with two classes of same type  Automatic conversion to more than one type - fan- out  Adds hidden activities (copy-constructor etc)
  • 34. Unit Summary In this unit you have covered …  Operator overloading  Different types of operator  Operators that cannot be overloaded  Inheritance and overloading  Automatic type conversion