SlideShare a Scribd company logo
Chapter-15
Operator Overloading
Abu Saleh Musa Miah
M.Sc. Engg(On going)
University of Rajshahi
Operator Overloading
An operator function is created using the keyword operator. Operator
functions can be either members or nonmembers of a class.
Nonmember operator functions are almost always friend functions of
the class
Creating a Member Operator Function
A member operator function takes this general form:
ret-type class-name::operator#(arg-list)
{
// operations
}
• Operator functions return an object of the class
they operate on,
• But ret-type can be any valid type.
• The # is a placeholder. When you create an
operator function, substitute the operator for the #.
First example of operator overloading.
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt; }
void show() {
cout << longitude << " ";
cout << latitude << "n";
}
loc operator+(loc op2);
};// Overload + for loc.
loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.longitude +
longitude;
temp.latitude = op2.latitude + latitude;
return temp;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30);
ob1.show(); // displays 10 20
ob2.show(); // displays 5 30
ob1 = ob1 + ob2;
ob1.show(); // displays 15 50
return 0;
Creating a Member Operator Function
• Operator+() has only one parameter even though
it overloads the binary + operator.
• The reason that operator+() takes only one
parameter is that the operand on the left side of the
+ is passed implicitly to the function through The
this pointer.
• The operand on the right is passed in the
parameter op2.
• It is common for an overloaded operator function to
return an object of the class it operates upon.
• (ob1+ob2).show(); // displays outcome of ob1+ob2
• In this situation, ob1+ob2 generates a temporary
object that ceases to exist after the call to show()
terminates.
The next program adds three additional
overloaded operators to the loc class: the –,
the =, and the unary ++.
• Operator+() has only one parameter even though
it overloads the binary + operator.
• The reason that operator+() takes only one
parameter is that the operand on the left side of the
+ is passed implicitly to the function through The
this pointer.
• The operand on the right is passed in the
parameter op2.
• It is common for an overloaded operator function to
return an object of the class it operates upon.
• (ob1+ob2).show(); // displays outcome of ob1+ob2
• In this situation, ob1+ob2 generates a temporary
Overloading Constructor Functions:
The next program adds three additional overloaded operators to the loc
class: the –, the =, and the unary ++.
class loc {
int longitude, latitude;
public:
loc() {} // needed to
construct temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "n";
loc operator+(loc op2);
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};// Overload + for loc.
loc loc::operator+(loc op2)
{
loc temp;
temp.longitude = op2.longitude +
longitude;
temp.latitude = op2.latitude + latitude;
return temp;
}
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude -
op2.longitude;
Overloading Constructor Functions:
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return
object that generated call
}// Overload prefix ++ for
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5, 30), ob3(90,
90);
ob1.show();
ob2.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob1.show(); // displays 12 22
ob2.show(); // displays 12 22
ob1 = ob2 = ob3; // multiple
assignment
ob1.show(); // displays 90 90
ob2.show(); // displays 90 90
return 0;
}
loc operator++(int x);
If the ++ precedes its operand, the operator++() function is called. If the ++
follows its operand, the operator++(int x) is called and x has the value
zero.
Here are the general forms for the prefix and postfix ++ and – – operator
functions.
Creating Prefix and Postfix Forms of the
Increment and Decrement Operators
// Prefix increment
type operator++( ) {
// body of prefix
operator
}
// Postfix increment
type operator++(int x) {
// body of postfix
operator
// Prefix decrement
type operator– –( ) {
// body of prefix
operator
}
// Postfix decrement
type operator– –(int x) {
// body of postfix
operator
Overloading the Shorthand Operators
loc loc::operator+=(loc op2)
{
longitude = op2.longitude + longitude;
latitude = op2.latitude + latitude;
return *this;
}
When overloading one of these operators, keep in mind that you are simply
combining an assignment with another type of operation.
Operator Overloading Restrictions
 There are some restrictions that apply to operator overloading.
 You cannot alter the precedence of an operator.
 You cannot change the number of operands that an operator takes.
 operator functions cannot have default arguments. Finally,these
operators cannot be overloaded:
. : : .* ?
Operator Overloading Using a Friend Function
You can overload an operator for a class by using a nonmember function,
which is usually a friend of the class. Since a friend function is not a
member of the class, it does not have a this pointer.
You can overload an operator for a class by using a nonmember function,
which is usually a friend of the class. Since a friend function is not a
member of the class, it does not have a this pointer
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {} // needed to construct
temporaries
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "n";
}
friend loc operator+(loc op1, loc op2); //
now a friend
loc operator-(loc op2);
loc operator=(loc op2);
loc operator++();
};
// Now, + is overloaded using friend
function.
loc operator+(loc op1, loc op2)
{
loc temp;
temp.longitude = op1.longitude +
op2.longitude;
temp.latitude = op1.latitude +
op2.latitude;
Operator Overloading Using a Friend Function
// Overload - for loc.
loc loc::operator-(loc op2)
{
loc temp;
// notice order of operands
temp.longitude = longitude -
op2.longitude;
temp.latitude = latitude - op2.latitude;
return temp;
}
// Overload assignment for
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object that
generated call
// Overload ++ for loc.
loc loc::operator++()
{
longitude++;
latitude++;
return *this;
}
int main()
{
loc ob1(10, 20), ob2( 5,
30);
ob1 = ob1 + ob2;
ob1.show();
return 0;
}
Operator Overloading Using a Friend Function
There are some restrictions that apply
to friend operator functions.
First, you may not overload the =, ( ), [
], or –> operators by using a friend
function.
 Second, as explained in the next
section, when overloading the
increment or decrement operators,
you will need to use a reference
Using a Friend to Overload ++ or – –
 If you want to use a friend function to overload the increment or decrement operators, you
must pass the operand as a reference parameter. his is because friend functions do not
have this pointers.
 The main goal of unary operator modificatin value of variable.
 Normaly friend function worked as a call by value so there is no way to modifi value of
variable without passing reference.
#include <iostream>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt; }
void show() {
cout << longitude << " ";
cout << latitude << "n";
}
loc operator=(loc op2);
friend loc operator++(loc
&op);
friend loc operator--(loc &op);
Using a Friend to Overload ++ or – –
// Make op-- a friend; use reference.
loc operator--(loc &op)
{
op.longitude--;
op.latitude--;
return op;
}
int main()
{
loc ob1(10, 20), ob2;
ob1.show();
++ob1;
ob1.show(); // displays 11 21
ob2 = ++ob1;
ob2.show(); // displays 12 22
--ob2;
ob2.show(); // displays 11 21
return 0;
}
// Overload assignment for loc.
loc loc::operator=(loc op2)
{
longitude = op2.longitude;
latitude = op2.latitude;
return *this; // i.e., return object
that generated call
}
// Now a friend; use a reference
parameter.
loc operator++(loc &op)
{
op.longitude++;
op.latitude++;
return op;
}
Overloading new and delete
It is possible to overload new and delete. You might choose to do this if
you want
to use some special allocation method.
The skeletons for the functions that overload new and delete are
shown here:
// Allocate an object.
void *operator new(size_t size)
{
/* Perform allocation. Throw bad_alloc on failure.
Constructor called automatically. */
return pointer_to_memory;
}
// Delete an object.
void operator delete(void *p)
{
/* Free memory pointed to by p.
Destructor called automatically. */
}
Overloading new and delete
// new
{
void *p;
cout << "In overloaded new.n";
p = malloc(size);
if(!p) {
bad_alloc ba;
throw ba;
}
return p;
}// delete overloaded relative to loc.
void loc::operator delete(void *p)
{
cout << "In overloaded delete.n";
free(p); }
overloaded for the loc class:
#include <iostream>
#include <cstdlib>
#include <new>
using namespace std;
class loc {
int longitude, latitude;
public:
loc() {}
loc(int lg, int lt) {
longitude = lg;
latitude = lt;
}
void show() {
cout << longitude << " ";
cout << latitude << "n";
}
void *operator new(size_t
size);
Overloading new and delete
p1->show();
p2->show();
delete p1;
c e
delete p2;
return 0;
}
Output from this program is shown
here.
In overloaded new.
In overloaded new.
10 20
-10 -20
In overloaded delete.
In overloaded delete.
int main()
{
loc *p1, *p2;
try {
p1 = new loc (10, 20);
} catch (bad_alloc xa) {
cout << "Allocation error for
p1.n";
return 1;
}
try {
p2 = new loc (-10, -20);
} catch (bad_alloc xa) {
cout << "Allocation error for
p2.n";
return 1;;
}
Overloading the nothrow Version of new and delete
// Nothrow version of new.
void *operator new(size_t size, const nothrow_t &n)
{
// Perform allocation.
if(success) return pointer_to_memory;
else return 0;
}// Nothrow version of new for arrays.
void *operator new[](size_t size, const nothrow_t &n)
{// Perform allocation.
if(success) return pointer_to_memory;
else return 0;
}void operator delete(void *p, const nothrow_t &n)
{
// free memory
}
void operator delete[](void *p, const nothrow_t &n)
{
// free memory
}
Chapter 15
End
Thank you

More Related Content

What's hot

Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
Chris Wilkes
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
Christoph Bauer
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
Vincent Pradeilles
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
CocoaHeads France
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
Janani Anbarasan
 
Overloading
OverloadingOverloading
Overloading
Mukhtar_Hunzai
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
MFC Message Handling
MFC Message HandlingMFC Message Handling
MFC Message Handling
Janani Anbarasan
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Badoo Development
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
John De Goes
 
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
NAVER Engineering
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
Vincent Pradeilles
 
The Ring programming language version 1.2 book - Part 57 of 84
The Ring programming language version 1.2 book - Part 57 of 84The Ring programming language version 1.2 book - Part 57 of 84
The Ring programming language version 1.2 book - Part 57 of 84
Mahmoud Samir Fayed
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloadingDeepak Singh
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
Badoo Development
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
John De Goes
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
Ruslan Shevchenko
 
Swift で数学のススメ 〜 プログラミングと数学は同時に学べ
Swift で数学のススメ 〜 プログラミングと数学は同時に学べSwift で数学のススメ 〜 プログラミングと数学は同時に学べ
Swift で数学のススメ 〜 プログラミングと数学は同時に学べ
Taketo Sano
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
John De Goes
 
視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて
Ray Fix
 

What's hot (20)

Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Advanced functional programing in Swift
Advanced functional programing in SwiftAdvanced functional programing in Swift
Advanced functional programing in Swift
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
C++ idioms.pptx
C++ idioms.pptxC++ idioms.pptx
C++ idioms.pptx
 
Overloading
OverloadingOverloading
Overloading
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo JobyC++ and OOPS Crash Course by ACM DBIT | Grejo Joby
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
 
MFC Message Handling
MFC Message HandlingMFC Message Handling
MFC Message Handling
 
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature developmentCocoaheads Meetup / Kateryna Trofimenko / Feature development
Cocoaheads Meetup / Kateryna Trofimenko / Feature development
 
All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!All Aboard The Scala-to-PureScript Express!
All Aboard The Scala-to-PureScript Express!
 
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
200819 NAVER TECH CONCERT 03_화려한 코루틴이 내 앱을 감싸네! 코루틴으로 작성해보는 깔끔한 비동기 코드
 
Cocoa heads 09112017
Cocoa heads 09112017Cocoa heads 09112017
Cocoa heads 09112017
 
The Ring programming language version 1.2 book - Part 57 of 84
The Ring programming language version 1.2 book - Part 57 of 84The Ring programming language version 1.2 book - Part 57 of 84
The Ring programming language version 1.2 book - Part 57 of 84
 
Chapter24 operator-overloading
Chapter24 operator-overloadingChapter24 operator-overloading
Chapter24 operator-overloading
 
Cocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magicCocoaheads Meetup / Alex Zimin / Swift magic
Cocoaheads Meetup / Alex Zimin / Swift magic
 
Halogen: Past, Present, and Future
Halogen: Past, Present, and FutureHalogen: Past, Present, and Future
Halogen: Past, Present, and Future
 
Csp scala wixmeetup2016
Csp scala wixmeetup2016Csp scala wixmeetup2016
Csp scala wixmeetup2016
 
Swift で数学のススメ 〜 プログラミングと数学は同時に学べ
Swift で数学のススメ 〜 プログラミングと数学は同時に学べSwift で数学のススメ 〜 プログラミングと数学は同時に学べ
Swift で数学のススメ 〜 プログラミングと数学は同時に学べ
 
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
The Easy-Peasy-Lemon-Squeezy, Statically-Typed, Purely Functional Programming...
 
視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて視覚化とSwiftのタイプについて
視覚化とSwiftのタイプについて
 

Viewers also liked

Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Abu Saleh
 
Vbmca204821311240
Vbmca204821311240Vbmca204821311240
Vbmca204821311240Ayushi Jain
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
Nilesh Dalvi
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.pptTareq Hasan
 
Data warehousing
Data warehousingData warehousing
Data warehousing
Shruti Dalela
 
Data mining: Concepts and Techniques, Chapter12 outlier Analysis
Data mining: Concepts and Techniques, Chapter12 outlier Analysis Data mining: Concepts and Techniques, Chapter12 outlier Analysis
Data mining: Concepts and Techniques, Chapter12 outlier Analysis
Salah Amean
 
Data Mining:Concepts and Techniques, Chapter 8. Classification: Basic Concepts
Data Mining:Concepts and Techniques, Chapter 8. Classification: Basic ConceptsData Mining:Concepts and Techniques, Chapter 8. Classification: Basic Concepts
Data Mining:Concepts and Techniques, Chapter 8. Classification: Basic Concepts
Salah Amean
 
Data Mining: Classification and analysis
Data Mining: Classification and analysisData Mining: Classification and analysis
Data Mining: Classification and analysis
DataminingTools Inc
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Abu Saleh
 
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Abu Saleh
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Abu Saleh
 
Gulabs Ppt On Data Warehousing And Mining
Gulabs Ppt On Data Warehousing And MiningGulabs Ppt On Data Warehousing And Mining
Gulabs Ppt On Data Warehousing And Mininggulab sharma
 
Data warehouse and data mining
Data warehouse and data miningData warehouse and data mining
Data warehouse and data miningRohit Kumar
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Abu Saleh
 
2.1 Data Mining-classification Basic concepts
2.1 Data Mining-classification Basic concepts2.1 Data Mining-classification Basic concepts
2.1 Data Mining-classification Basic concepts
Krish_ver2
 
Data Mining and Data Warehousing
Data Mining and Data WarehousingData Mining and Data Warehousing
Data Mining and Data Warehousing
Amdocs
 

Viewers also liked (19)

Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12Lecture 2, c++(complete reference,herbet sheidt)chapter-12
Lecture 2, c++(complete reference,herbet sheidt)chapter-12
 
Vbmca204821311240
Vbmca204821311240Vbmca204821311240
Vbmca204821311240
 
Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
Data warehousing
Data warehousingData warehousing
Data warehousing
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
 
Data warehousing
Data warehousingData warehousing
Data warehousing
 
Data mining: Concepts and Techniques, Chapter12 outlier Analysis
Data mining: Concepts and Techniques, Chapter12 outlier Analysis Data mining: Concepts and Techniques, Chapter12 outlier Analysis
Data mining: Concepts and Techniques, Chapter12 outlier Analysis
 
Data Mining:Concepts and Techniques, Chapter 8. Classification: Basic Concepts
Data Mining:Concepts and Techniques, Chapter 8. Classification: Basic ConceptsData Mining:Concepts and Techniques, Chapter 8. Classification: Basic Concepts
Data Mining:Concepts and Techniques, Chapter 8. Classification: Basic Concepts
 
Data Mining: Classification and analysis
Data Mining: Classification and analysisData Mining: Classification and analysis
Data Mining: Classification and analysis
 
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13Lecture 3, c++(complete reference,herbet sheidt)chapter-13
Lecture 3, c++(complete reference,herbet sheidt)chapter-13
 
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16Lecture 6, c++(complete reference,herbet sheidt)chapter-16
Lecture 6, c++(complete reference,herbet sheidt)chapter-16
 
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14Lecture 4, c++(complete reference,herbet sheidt)chapter-14
Lecture 4, c++(complete reference,herbet sheidt)chapter-14
 
C++ Complete Reference
C++ Complete ReferenceC++ Complete Reference
C++ Complete Reference
 
Gulabs Ppt On Data Warehousing And Mining
Gulabs Ppt On Data Warehousing And MiningGulabs Ppt On Data Warehousing And Mining
Gulabs Ppt On Data Warehousing And Mining
 
Data warehouse and data mining
Data warehouse and data miningData warehouse and data mining
Data warehouse and data mining
 
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
Lecture 7, c++(complete reference,herbet sheidt)chapter-17.
 
2.1 Data Mining-classification Basic concepts
2.1 Data Mining-classification Basic concepts2.1 Data Mining-classification Basic concepts
2.1 Data Mining-classification Basic concepts
 
Data Mining and Data Warehousing
Data Mining and Data WarehousingData Mining and Data Warehousing
Data Mining and Data Warehousing
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Similar to Lecture 5, c++(complete reference,herbet sheidt)chapter-15

Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
esuEthopi
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
Md. Ashraful Islam
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloadingPrincess Sam
 
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
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
zindadili
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloadingPrincess Sam
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
sheibansari
 
Operator Overloading in C++
Operator Overloading in C++Operator Overloading in C++
Operator Overloading in C++
Mohammed Sikander
 
3. Polymorphism.pptx
3. Polymorphism.pptx3. Polymorphism.pptx
3. Polymorphism.pptx
ChhaviCoachingCenter
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Pranali Chaudhari
 
Operator overloading
Operator overloadingOperator overloading
Operator overloadingKumar
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
Ramish Suleman
 
operator overloading
operator overloadingoperator overloading
operator overloading
Sorath Peetamber
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
rebin5725
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
Prof Ansari
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
zindadili
 
Unit ii
Unit iiUnit ii
Unit ii
snehaarao19
 

Similar to Lecture 5, c++(complete reference,herbet sheidt)chapter-15 (20)

Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
Unary operator overloading
Unary operator overloadingUnary operator overloading
Unary operator overloading
 
Oops
OopsOops
Oops
 
Lec 26.27-operator overloading
Lec 26.27-operator overloadingLec 26.27-operator overloading
Lec 26.27-operator overloading
 
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
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptxObject Oriented Programming using C++: Ch08 Operator Overloading.pptx
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Lec 28 - operator overloading
Lec 28 - operator overloadingLec 28 - operator overloading
Lec 28 - operator overloading
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Operator Overloading in C++
Operator Overloading in C++Operator Overloading in C++
Operator Overloading in C++
 
3. Polymorphism.pptx
3. Polymorphism.pptx3. Polymorphism.pptx
3. Polymorphism.pptx
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
operator overloading
operator overloadingoperator overloading
operator overloading
 
Functions in C++ programming language.pptx
Functions in  C++ programming language.pptxFunctions in  C++ programming language.pptx
Functions in C++ programming language.pptx
 
overloading in C++
overloading in C++overloading in C++
overloading in C++
 
Operator overloaing
Operator overloaingOperator overloaing
Operator overloaing
 
Unit ii
Unit iiUnit ii
Unit ii
 

Recently uploaded

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
tarandeep35
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
Wasim Ak
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
ArianaBusciglio
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
AG2 Design
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Akanksha trivedi rama nursing college kanpur.
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
Celine George
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
Academy of Science of South Africa
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Dr. Vinod Kumar Kanvaria
 
MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
scholarhattraining
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
amberjdewit93
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
Levi Shapiro
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
deeptiverma2406
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
TechSoup
 
What is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptxWhat is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptx
christianmathematics
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
National Information Standards Organization (NISO)
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
goswamiyash170123
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
Scholarhat
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
eBook.com.bd (প্রয়োজনীয় বাংলা বই)
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
IreneSebastianRueco1
 

Recently uploaded (20)

S1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptxS1-Introduction-Biopesticides in ICM.pptx
S1-Introduction-Biopesticides in ICM.pptx
 
Normal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of LabourNormal Labour/ Stages of Labour/ Mechanism of Labour
Normal Labour/ Stages of Labour/ Mechanism of Labour
 
Group Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana BuscigliopptxGroup Presentation 2 Economics.Ariana Buscigliopptx
Group Presentation 2 Economics.Ariana Buscigliopptx
 
Delivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and TrainingDelivering Micro-Credentials in Technical and Vocational Education and Training
Delivering Micro-Credentials in Technical and Vocational Education and Training
 
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama UniversityNatural birth techniques - Mrs.Akanksha Trivedi Rama University
Natural birth techniques - Mrs.Akanksha Trivedi Rama University
 
How to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold MethodHow to Build a Module in Odoo 17 Using the Scaffold Method
How to Build a Module in Odoo 17 Using the Scaffold Method
 
South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)South African Journal of Science: Writing with integrity workshop (2024)
South African Journal of Science: Writing with integrity workshop (2024)
 
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
Exploiting Artificial Intelligence for Empowering Researchers and Faculty, In...
 
MERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDFMERN Stack Developer Roadmap By ScholarHat PDF
MERN Stack Developer Roadmap By ScholarHat PDF
 
Digital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental DesignDigital Artefact 1 - Tiny Home Environmental Design
Digital Artefact 1 - Tiny Home Environmental Design
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
June 3, 2024 Anti-Semitism Letter Sent to MIT President Kornbluth and MIT Cor...
 
Best Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDABest Digital Marketing Institute In NOIDA
Best Digital Marketing Institute In NOIDA
 
Introduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp NetworkIntroduction to AI for Nonprofits with Tapp Network
Introduction to AI for Nonprofits with Tapp Network
 
What is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptxWhat is the purpose of studying mathematics.pptx
What is the purpose of studying mathematics.pptx
 
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
Pollock and Snow "DEIA in the Scholarly Landscape, Session One: Setting Expec...
 
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdfMASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
MASS MEDIA STUDIES-835-CLASS XI Resource Material.pdf
 
Azure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHatAzure Interview Questions and Answers PDF By ScholarHat
Azure Interview Questions and Answers PDF By ScholarHat
 
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdfবাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
বাংলাদেশ অর্থনৈতিক সমীক্ষা (Economic Review) ২০২৪ UJS App.pdf
 
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
RPMS TEMPLATE FOR SCHOOL YEAR 2023-2024 FOR TEACHER 1 TO TEACHER 3
 

Lecture 5, c++(complete reference,herbet sheidt)chapter-15

  • 1. Chapter-15 Operator Overloading Abu Saleh Musa Miah M.Sc. Engg(On going) University of Rajshahi
  • 2. Operator Overloading An operator function is created using the keyword operator. Operator functions can be either members or nonmembers of a class. Nonmember operator functions are almost always friend functions of the class
  • 3. Creating a Member Operator Function A member operator function takes this general form: ret-type class-name::operator#(arg-list) { // operations } • Operator functions return an object of the class they operate on, • But ret-type can be any valid type. • The # is a placeholder. When you create an operator function, substitute the operator for the #.
  • 4. First example of operator overloading. #include <iostream> using namespace std; class loc { int longitude, latitude; public: loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "n"; } loc operator+(loc op2); };// Overload + for loc. loc loc::operator+(loc op2) { loc temp; temp.longitude = op2.longitude + longitude; temp.latitude = op2.latitude + latitude; return temp; } int main() { loc ob1(10, 20), ob2( 5, 30); ob1.show(); // displays 10 20 ob2.show(); // displays 5 30 ob1 = ob1 + ob2; ob1.show(); // displays 15 50 return 0;
  • 5. Creating a Member Operator Function • Operator+() has only one parameter even though it overloads the binary + operator. • The reason that operator+() takes only one parameter is that the operand on the left side of the + is passed implicitly to the function through The this pointer. • The operand on the right is passed in the parameter op2. • It is common for an overloaded operator function to return an object of the class it operates upon. • (ob1+ob2).show(); // displays outcome of ob1+ob2 • In this situation, ob1+ob2 generates a temporary object that ceases to exist after the call to show() terminates.
  • 6. The next program adds three additional overloaded operators to the loc class: the –, the =, and the unary ++. • Operator+() has only one parameter even though it overloads the binary + operator. • The reason that operator+() takes only one parameter is that the operand on the left side of the + is passed implicitly to the function through The this pointer. • The operand on the right is passed in the parameter op2. • It is common for an overloaded operator function to return an object of the class it operates upon. • (ob1+ob2).show(); // displays outcome of ob1+ob2 • In this situation, ob1+ob2 generates a temporary
  • 7. Overloading Constructor Functions: The next program adds three additional overloaded operators to the loc class: the –, the =, and the unary ++. class loc { int longitude, latitude; public: loc() {} // needed to construct temporaries loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "n"; loc operator+(loc op2); loc operator-(loc op2); loc operator=(loc op2); loc operator++(); };// Overload + for loc. loc loc::operator+(loc op2) { loc temp; temp.longitude = op2.longitude + longitude; temp.latitude = op2.latitude + latitude; return temp; } // Overload - for loc. loc loc::operator-(loc op2) { loc temp; // notice order of operands temp.longitude = longitude - op2.longitude;
  • 8. Overloading Constructor Functions: loc loc::operator=(loc op2) { longitude = op2.longitude; latitude = op2.latitude; return *this; // i.e., return object that generated call }// Overload prefix ++ for loc loc::operator++() { longitude++; latitude++; return *this; } int main() { loc ob1(10, 20), ob2( 5, 30), ob3(90, 90); ob1.show(); ob2.show(); ++ob1; ob1.show(); // displays 11 21 ob2 = ++ob1; ob1.show(); // displays 12 22 ob2.show(); // displays 12 22 ob1 = ob2 = ob3; // multiple assignment ob1.show(); // displays 90 90 ob2.show(); // displays 90 90 return 0; }
  • 9. loc operator++(int x); If the ++ precedes its operand, the operator++() function is called. If the ++ follows its operand, the operator++(int x) is called and x has the value zero. Here are the general forms for the prefix and postfix ++ and – – operator functions. Creating Prefix and Postfix Forms of the Increment and Decrement Operators // Prefix increment type operator++( ) { // body of prefix operator } // Postfix increment type operator++(int x) { // body of postfix operator // Prefix decrement type operator– –( ) { // body of prefix operator } // Postfix decrement type operator– –(int x) { // body of postfix operator
  • 10. Overloading the Shorthand Operators loc loc::operator+=(loc op2) { longitude = op2.longitude + longitude; latitude = op2.latitude + latitude; return *this; } When overloading one of these operators, keep in mind that you are simply combining an assignment with another type of operation.
  • 11. Operator Overloading Restrictions  There are some restrictions that apply to operator overloading.  You cannot alter the precedence of an operator.  You cannot change the number of operands that an operator takes.  operator functions cannot have default arguments. Finally,these operators cannot be overloaded: . : : .* ?
  • 12. Operator Overloading Using a Friend Function You can overload an operator for a class by using a nonmember function, which is usually a friend of the class. Since a friend function is not a member of the class, it does not have a this pointer. You can overload an operator for a class by using a nonmember function, which is usually a friend of the class. Since a friend function is not a member of the class, it does not have a this pointer #include <iostream> using namespace std; class loc { int longitude, latitude; public: loc() {} // needed to construct temporaries loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "n"; } friend loc operator+(loc op1, loc op2); // now a friend loc operator-(loc op2); loc operator=(loc op2); loc operator++(); }; // Now, + is overloaded using friend function. loc operator+(loc op1, loc op2) { loc temp; temp.longitude = op1.longitude + op2.longitude; temp.latitude = op1.latitude + op2.latitude;
  • 13. Operator Overloading Using a Friend Function // Overload - for loc. loc loc::operator-(loc op2) { loc temp; // notice order of operands temp.longitude = longitude - op2.longitude; temp.latitude = latitude - op2.latitude; return temp; } // Overload assignment for loc loc::operator=(loc op2) { longitude = op2.longitude; latitude = op2.latitude; return *this; // i.e., return object that generated call // Overload ++ for loc. loc loc::operator++() { longitude++; latitude++; return *this; } int main() { loc ob1(10, 20), ob2( 5, 30); ob1 = ob1 + ob2; ob1.show(); return 0; }
  • 14. Operator Overloading Using a Friend Function There are some restrictions that apply to friend operator functions. First, you may not overload the =, ( ), [ ], or –> operators by using a friend function.  Second, as explained in the next section, when overloading the increment or decrement operators, you will need to use a reference
  • 15. Using a Friend to Overload ++ or – –  If you want to use a friend function to overload the increment or decrement operators, you must pass the operand as a reference parameter. his is because friend functions do not have this pointers.  The main goal of unary operator modificatin value of variable.  Normaly friend function worked as a call by value so there is no way to modifi value of variable without passing reference. #include <iostream> using namespace std; class loc { int longitude, latitude; public: loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "n"; } loc operator=(loc op2); friend loc operator++(loc &op); friend loc operator--(loc &op);
  • 16. Using a Friend to Overload ++ or – – // Make op-- a friend; use reference. loc operator--(loc &op) { op.longitude--; op.latitude--; return op; } int main() { loc ob1(10, 20), ob2; ob1.show(); ++ob1; ob1.show(); // displays 11 21 ob2 = ++ob1; ob2.show(); // displays 12 22 --ob2; ob2.show(); // displays 11 21 return 0; } // Overload assignment for loc. loc loc::operator=(loc op2) { longitude = op2.longitude; latitude = op2.latitude; return *this; // i.e., return object that generated call } // Now a friend; use a reference parameter. loc operator++(loc &op) { op.longitude++; op.latitude++; return op; }
  • 17. Overloading new and delete It is possible to overload new and delete. You might choose to do this if you want to use some special allocation method. The skeletons for the functions that overload new and delete are shown here: // Allocate an object. void *operator new(size_t size) { /* Perform allocation. Throw bad_alloc on failure. Constructor called automatically. */ return pointer_to_memory; } // Delete an object. void operator delete(void *p) { /* Free memory pointed to by p. Destructor called automatically. */ }
  • 18. Overloading new and delete // new { void *p; cout << "In overloaded new.n"; p = malloc(size); if(!p) { bad_alloc ba; throw ba; } return p; }// delete overloaded relative to loc. void loc::operator delete(void *p) { cout << "In overloaded delete.n"; free(p); } overloaded for the loc class: #include <iostream> #include <cstdlib> #include <new> using namespace std; class loc { int longitude, latitude; public: loc() {} loc(int lg, int lt) { longitude = lg; latitude = lt; } void show() { cout << longitude << " "; cout << latitude << "n"; } void *operator new(size_t size);
  • 19. Overloading new and delete p1->show(); p2->show(); delete p1; c e delete p2; return 0; } Output from this program is shown here. In overloaded new. In overloaded new. 10 20 -10 -20 In overloaded delete. In overloaded delete. int main() { loc *p1, *p2; try { p1 = new loc (10, 20); } catch (bad_alloc xa) { cout << "Allocation error for p1.n"; return 1; } try { p2 = new loc (-10, -20); } catch (bad_alloc xa) { cout << "Allocation error for p2.n"; return 1;; }
  • 20. Overloading the nothrow Version of new and delete // Nothrow version of new. void *operator new(size_t size, const nothrow_t &n) { // Perform allocation. if(success) return pointer_to_memory; else return 0; }// Nothrow version of new for arrays. void *operator new[](size_t size, const nothrow_t &n) {// Perform allocation. if(success) return pointer_to_memory; else return 0; }void operator delete(void *p, const nothrow_t &n) { // free memory } void operator delete[](void *p, const nothrow_t &n) { // free memory }