SlideShare a Scribd company logo
1 of 7
CSE 332: C++ Overloading
Overview of C++ Overloading
• Overloading occurs when the same operator or
function name is used with different signatures
• Both operators and functions can be overloaded
• Different definitions must be distinguished by their
signatures (otherwise which to call is ambiguous)
– Reminder: signature is the operator/function name and the
ordered list of its argument types
– E.g., add(int,long) and add(long,int) have different
signatures
– E.g., add(const Base &) and add(const Derived &)
have different signatures, even if Derived is-a Base
– Most specific match is used to select which one to call
CSE 332: C++ Overloading
Overloading vs. Overriding
• Overriding a base class member function is
similar to overloading a function or operator
– But for overriding, definitions are distinguished by
their scopes rather than by their signatures
• C++ can distinguish method definitions
according to either static or dynamic type
– Depends on whether a method is virtual or not
– Depends on whether called via a reference or
pointer vs. directly on an object
– Depends on whether the call states the scope
explicitly (e.g., Foo::baz();)
CSE 332: C++ Overloading
Function Overloading
class A {
public:
int add(int i, int j);
// not allowed, would be
// ambiguous with above:
// long add(int m, int n);
// Ok, different signature
long add(long m, long n);
};
int
main (int argc, char **argv) {
int a = 7;
int b = 8;
int c = add(a, b);
return 0;
}
• Calls to overloaded functions and
operators are resolved by
– Finding all possible matches based
on passed arguments
• May involve type promotion
• May involve instantiating templates
– Finding the “best match” among
those possible matches
• Signature does not include the
return type
– Which might not help even if it did,
i.e., calls may ignore result
– So, overloading can’t be resolved by
return type alone
– Compiler generates an error if the
call can’t be resolved
CSE 332: C++ Overloading
Operator Overloading
class A {
friend ostream &operator<<
(ostream &, const A &);
private:
int m_;
};
ostream &operator<<
(ostream &out, const A &a) {
out << "A::m_ = " << a.m_;
return out;
}
int main () {
A a;
cout << a << endl;
return 0;
}
• Similar to function
overloading
– Resolved by signature
– Best match is used
• But the list of operators and
the “arity” of each is fixed
– Can’t invent operators (e.g.,
like ** for exponentiation )
– Must use same number of
arguments as for built-in types
(except for operator())
– Some operators are off limits
:: (scope) ?: (conditional)
.* (member dereference)
. (member) sizeof
typeid (RTTI)
CSE 332: C++ Overloading
Operator Symmetry, Precedence
class Complex {
public:
// Constructor
Complex (double r, double i);
friend Complex operator*
(const Complex &, const Complex &);
// but not friend Complex operator^
// (const Complex &, const Complex &);
private:
int real_;
int imaginary_;
};
// multiplication works just fine
Complex operator* (const Complex &,
const Complex &);
// exponentiation operator unworkable
// Complex operator^ (const Complex &,
// const Complex &);
• Make arithmetic
operators symmetric
– As non-member friends
– Return result by value
– Don’t mix base and
derived types in their
parameter lists
• Operators for user-
defined types obey the
same precedence rules
as for built-in types
– Can lead to some
unexpected mistakes
– E.g., if uncommented
exponentiation for
a + b * c ^ 2
CSE 332: C++ Overloading
Member vs. Non-Member Overloading
// declarations in .h file
class A {
public:
friend bool operator<
(const A &, const A &);
A operator++(); // prefix
A operator++(int); // postfix
private:
int m_;
};
bool operator==(const A &lhs,
const A &rhs);
// definitions in .cpp file
bool operator==(const A &lhs,
const A &rhs)
{return lhs.m_ == rhs.m_;}
A A::operator++() // prefix
{++m_; return *this;}
A A::operator++(int) // postfix
{A ret(*this); ++*this; return ret;}
• Remember a this pointer is passed
to any non-static member function
– Object doesn’t appear in parameters
– For non-member functions and
operators all parameters are listed
• The rules about operator arity are
obeyed in code on left
– Operator == is binary
– Prefix/postfix ++ are unary, parameter
for postfix distinguishes its signature
• Must declare and define [] and ==
and -> and () as member operators
• Non-member operators are needed
when working with classes you wrote
and classes you didn’t write
– E.g., ostream << and istream >>
• Non-member operators are also
useful to preserve symmetry
– E.g., for arithmetic/relational operators
– May help to avoid unexpected type
conversions, especially with an
inheritance hierarchy
CSE 332: C++ Overloading
Summary: Tips on Overloading
• Use virtual overriding when you want to substitute
different subtypes polymorphically
– E.g., move() in derived and base classes
• Use overloading when you want to provide related
interfaces to similar abstractions
– E.g., migrate(Bird &) vs. migrate(Elephant &)
– Make[] -> () = *= ++ -- etc. members
– Make << >> + * - / == < etc. non-members
• Use different names when the abstractions differ
– E.g., fly() versus walk()

More Related Content

What's hot

08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingabhay singh
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpprajshreemuthiah
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++gourav kottawar
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingRai University
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadngpreethalal
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator OverloadingHadziq Fabroyir
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingArunaDevi63
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)Ritika Sharma
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingDustin Chase
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overridingRajab Ali
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversionsAmogh Kalyanshetti
 

What's hot (20)

08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
Operator overloading and type conversion in cpp
Operator overloading and type conversion in cppOperator overloading and type conversion in cpp
Operator overloading and type conversion in cpp
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++operator overloading & type conversion in cpp over view || c++
operator overloading & type conversion in cpp over view || c++
 
Bca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloadingBca 2nd sem u-4 operator overloading
Bca 2nd sem u-4 operator overloading
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
 
Lecture5
Lecture5Lecture5
Lecture5
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading#OOP_D_ITS - 5th - C++ Oop Operator Overloading
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
operator overloading in C++
operator overloading in C++operator overloading in C++
operator overloading in C++
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Operator overloading and type conversions
Operator overloading and type conversionsOperator overloading and type conversions
Operator overloading and type conversions
 

Viewers also liked

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cppgourav kottawar
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handlingsanya6900
 
Functions
FunctionsFunctions
FunctionsOnline
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop pptdaxesh chauhan
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++LPU
 
C++ Function
C++ FunctionC++ Function
C++ FunctionHajar
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++Learn By Watch
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method OverridingMichael Heron
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++harman kaur
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)sanya6900
 

Viewers also liked (16)

operator overloading & type conversion in cpp
operator overloading & type conversion in cppoperator overloading & type conversion in cpp
operator overloading & type conversion in cpp
 
3 Function Overloading
3 Function Overloading3 Function Overloading
3 Function Overloading
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Templates exception handling
Templates exception handlingTemplates exception handling
Templates exception handling
 
Functions
FunctionsFunctions
Functions
 
Principles and advantages of oop ppt
Principles and advantages of oop pptPrinciples and advantages of oop ppt
Principles and advantages of oop ppt
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Function C++
Function C++ Function C++
Function C++
 
functions of C++
functions of C++functions of C++
functions of C++
 
C++ Function
C++ FunctionC++ Function
C++ Function
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Function overloading in c++
Function overloading in c++Function overloading in c++
Function overloading in c++
 
2CPP12 - Method Overriding
2CPP12 - Method Overriding2CPP12 - Method Overriding
2CPP12 - Method Overriding
 
operator overloading in c++
operator overloading in c++operator overloading in c++
operator overloading in c++
 
Inheritance (1)
Inheritance (1)Inheritance (1)
Inheritance (1)
 

Similar to C++ overloading (20)

Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Operator overloading (binary)
Operator overloading (binary)Operator overloading (binary)
Operator overloading (binary)
 
C_plus_plus
C_plus_plusC_plus_plus
C_plus_plus
 
OOPS-Seminar.pdf
OOPS-Seminar.pdfOOPS-Seminar.pdf
OOPS-Seminar.pdf
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
Overloading
OverloadingOverloading
Overloading
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
OODP UNIT 2 Function overloading
OODP UNIT 2 Function overloadingOODP UNIT 2 Function overloading
OODP UNIT 2 Function overloading
 
c++ UNIT II.pptx
c++ UNIT II.pptxc++ UNIT II.pptx
c++ UNIT II.pptx
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Cpp (C++)
Cpp (C++)Cpp (C++)
Cpp (C++)
 
Oops
OopsOops
Oops
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
C++ language
C++ languageC++ language
C++ language
 
Operator overloading C++
Operator overloading C++Operator overloading C++
Operator overloading C++
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
C++ tutorials
C++ tutorialsC++ tutorials
C++ tutorials
 
Learn c++ Programming Language
Learn c++ Programming LanguageLearn c++ Programming Language
Learn c++ Programming Language
 
Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3Object Oriented Programming using C++ - Part 3
Object Oriented Programming using C++ - Part 3
 
Function Overloading.ppt
Function Overloading.pptFunction Overloading.ppt
Function Overloading.ppt
 

More from sanya6900

.Net framework
.Net framework.Net framework
.Net frameworksanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IISsanya6900
 
Type conversions
Type conversionsType conversions
Type conversionssanya6900
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++sanya6900
 
Memory allocation
Memory allocationMemory allocation
Memory allocationsanya6900
 
File handling in_c
File handling in_cFile handling in_c
File handling in_csanya6900
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03sanya6900
 

More from sanya6900 (10)

.Net framework
.Net framework.Net framework
.Net framework
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
INTRODUCTION TO IIS
INTRODUCTION TO IISINTRODUCTION TO IIS
INTRODUCTION TO IIS
 
Type conversions
Type conversionsType conversions
Type conversions
 
operators and expressions in c++
 operators and expressions in c++ operators and expressions in c++
operators and expressions in c++
 
Memory allocation
Memory allocationMemory allocation
Memory allocation
 
File handling in_c
File handling in_cFile handling in_c
File handling in_c
 
Ch7
Ch7Ch7
Ch7
 
Cpphtp4 ppt 03
Cpphtp4 ppt 03Cpphtp4 ppt 03
Cpphtp4 ppt 03
 
Pointers
PointersPointers
Pointers
 

Recently uploaded

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEroselinkalist12
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...Chandu841456
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxDeepakSakkari2
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixingviprabot1
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage examplePragyanshuParadkar1
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 

Recently uploaded (20)

INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETEINFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
INFLUENCE OF NANOSILICA ON THE PROPERTIES OF CONCRETE
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...An experimental study in using natural admixture as an alternative for chemic...
An experimental study in using natural admixture as an alternative for chemic...
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
Biology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptxBiology for Computer Engineers Course Handout.pptx
Biology for Computer Engineers Course Handout.pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
Effects of rheological properties on mixing
Effects of rheological properties on mixingEffects of rheological properties on mixing
Effects of rheological properties on mixing
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
DATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage exampleDATA ANALYTICS PPT definition usage example
DATA ANALYTICS PPT definition usage example
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 

C++ overloading

  • 1. CSE 332: C++ Overloading Overview of C++ Overloading • Overloading occurs when the same operator or function name is used with different signatures • Both operators and functions can be overloaded • Different definitions must be distinguished by their signatures (otherwise which to call is ambiguous) – Reminder: signature is the operator/function name and the ordered list of its argument types – E.g., add(int,long) and add(long,int) have different signatures – E.g., add(const Base &) and add(const Derived &) have different signatures, even if Derived is-a Base – Most specific match is used to select which one to call
  • 2. CSE 332: C++ Overloading Overloading vs. Overriding • Overriding a base class member function is similar to overloading a function or operator – But for overriding, definitions are distinguished by their scopes rather than by their signatures • C++ can distinguish method definitions according to either static or dynamic type – Depends on whether a method is virtual or not – Depends on whether called via a reference or pointer vs. directly on an object – Depends on whether the call states the scope explicitly (e.g., Foo::baz();)
  • 3. CSE 332: C++ Overloading Function Overloading class A { public: int add(int i, int j); // not allowed, would be // ambiguous with above: // long add(int m, int n); // Ok, different signature long add(long m, long n); }; int main (int argc, char **argv) { int a = 7; int b = 8; int c = add(a, b); return 0; } • Calls to overloaded functions and operators are resolved by – Finding all possible matches based on passed arguments • May involve type promotion • May involve instantiating templates – Finding the “best match” among those possible matches • Signature does not include the return type – Which might not help even if it did, i.e., calls may ignore result – So, overloading can’t be resolved by return type alone – Compiler generates an error if the call can’t be resolved
  • 4. CSE 332: C++ Overloading Operator Overloading class A { friend ostream &operator<< (ostream &, const A &); private: int m_; }; ostream &operator<< (ostream &out, const A &a) { out << "A::m_ = " << a.m_; return out; } int main () { A a; cout << a << endl; return 0; } • Similar to function overloading – Resolved by signature – Best match is used • But the list of operators and the “arity” of each is fixed – Can’t invent operators (e.g., like ** for exponentiation ) – Must use same number of arguments as for built-in types (except for operator()) – Some operators are off limits :: (scope) ?: (conditional) .* (member dereference) . (member) sizeof typeid (RTTI)
  • 5. CSE 332: C++ Overloading Operator Symmetry, Precedence class Complex { public: // Constructor Complex (double r, double i); friend Complex operator* (const Complex &, const Complex &); // but not friend Complex operator^ // (const Complex &, const Complex &); private: int real_; int imaginary_; }; // multiplication works just fine Complex operator* (const Complex &, const Complex &); // exponentiation operator unworkable // Complex operator^ (const Complex &, // const Complex &); • Make arithmetic operators symmetric – As non-member friends – Return result by value – Don’t mix base and derived types in their parameter lists • Operators for user- defined types obey the same precedence rules as for built-in types – Can lead to some unexpected mistakes – E.g., if uncommented exponentiation for a + b * c ^ 2
  • 6. CSE 332: C++ Overloading Member vs. Non-Member Overloading // declarations in .h file class A { public: friend bool operator< (const A &, const A &); A operator++(); // prefix A operator++(int); // postfix private: int m_; }; bool operator==(const A &lhs, const A &rhs); // definitions in .cpp file bool operator==(const A &lhs, const A &rhs) {return lhs.m_ == rhs.m_;} A A::operator++() // prefix {++m_; return *this;} A A::operator++(int) // postfix {A ret(*this); ++*this; return ret;} • Remember a this pointer is passed to any non-static member function – Object doesn’t appear in parameters – For non-member functions and operators all parameters are listed • The rules about operator arity are obeyed in code on left – Operator == is binary – Prefix/postfix ++ are unary, parameter for postfix distinguishes its signature • Must declare and define [] and == and -> and () as member operators • Non-member operators are needed when working with classes you wrote and classes you didn’t write – E.g., ostream << and istream >> • Non-member operators are also useful to preserve symmetry – E.g., for arithmetic/relational operators – May help to avoid unexpected type conversions, especially with an inheritance hierarchy
  • 7. CSE 332: C++ Overloading Summary: Tips on Overloading • Use virtual overriding when you want to substitute different subtypes polymorphically – E.g., move() in derived and base classes • Use overloading when you want to provide related interfaces to similar abstractions – E.g., migrate(Bird &) vs. migrate(Elephant &) – Make[] -> () = *= ++ -- etc. members – Make << >> + * - / == < etc. non-members • Use different names when the abstractions differ – E.g., fly() versus walk()