SlideShare une entreprise Scribd logo
1  sur  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()

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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)
 

Similaire à 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
 

Plus de 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
 

Plus de 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
 

Dernier

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
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerAnamika Sarkar
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction managementMariconPadriquez1
 
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
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxsomshekarkn64
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfAsst.prof M.Gokilavani
 
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
 

Dernier (20)

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
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube ExchangerStudy on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
Study on Air-Water & Water-Water Heat Exchange in a Finned Tube Exchanger
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
computer application and construction management
computer application and construction managementcomputer application and construction management
computer application and construction management
 
POWER SYSTEMS-1 Complete notes examples
POWER SYSTEMS-1 Complete notes  examplesPOWER SYSTEMS-1 Complete notes  examples
POWER SYSTEMS-1 Complete notes examples
 
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
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
🔝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...
 
lifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptxlifi-technology with integration of IOT.pptx
lifi-technology with integration of IOT.pptx
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptxExploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
Exploring_Network_Security_with_JA3_by_Rakesh Seal.pptx
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdfCCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
CCS355 Neural Networks & Deep Learning Unit 1 PDF notes with Question bank .pdf
 
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...
 

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()