SlideShare a Scribd company logo
More C++ Concepts Operator overloading Friend Function  This Operator  Inline Function
Operator overloading Programmer can use some operator symbols to define special member functions of a class Provides convenient notations for object behaviors
Why Operator Overloading int i, j, k;  // integers float m, n, p;  // floats k = i  +  j;   // integer addition and assignment p = m  +  n;   // floating addition and assignment The compiler overloads the  +  operator for built-in integer and float types by default, producing integer addition with i+j, and floating addition with m+n. We can make object operation look like individual int variable operation, using operator functions  Complex a,b,c; c = a  +  b;
Operator Overloading Syntax Syntax is: operator @(argument-list) --- operator is a function --- @ is one of C++ operator symbols (+, -, =, etc..) Examples: operator+ operator- operator* operator/
class CStr  { char *pData; int nLength; public: // 
 void cat(char *s); // 
   CStr  operator+ (CStr str1, CStr str2);   CStr  operator+ (CStr str, char *s);   CStr  operator+ (char *s, CStr str);   //accessors char* get_Data(); int get_Len();  }; Example of Operator Overloading void CStr::cat(char *s) { int n; char *pTemp; n=strlen(s); if (n==0) return; pTemp=new char[n+nLength+1]; if (pData)  strcpy(pTemp,pData); strcat(pTemp,s); pData=pTemp; nLength+=n; }
The Addition (+) Operator CStr CStr::operator+(CStr str1, CStr str2) { CStr new_string(str1); //call the copy constructor to initialize an  //entirely new CStr object with the first  //operand new_string.cat(str2.get_Data()); //concatenate the second operand onto the  //end of new_string return new_string; //call copy constructor to create a copy of  //the return value new_string } new_string str1 strlen(str1) strcat(str1,str2) strlen(str1)+strlen(str2)
How does it work? CStr first(“John”); CStr last(“Johnson”); CStr name(first+last); CStr CStr::operator+ (CStr str1,CStr str2) { CStr new_string(str1); new_string.cat(str2.get()); return new_string; } “ John Johnson” Temporary CStr object Copy constructor name
Implementing Operator Overloading Two ways: Implemented as  member functions   Implemented as  non-member or Friend functions the operator function may need to be declared as a friend if it requires access to protected or private data Expression  [email_address]  translates into a function call obj1.operator@(obj2) ,  if this function is defined within class obj1 operator@(obj1,obj2) ,  if this function is defined outside the class obj1
Defined as a member function Implementing Operator Overloading class Complex { ... public: ... Complex operator +(const Complex &op)  { double real  = _real  + op._real, imag = _imag + op._imag; return(Complex(real, imag)); } ... }; c = a+b; c =  a.operator+  (b);
Defined as a non-member function Implementing Operator Overloading class Complex { ... public: ... double real() { return _real; } //need access functions double imag() { return _imag; } ... }; Complex operator +(Complex &op1, Complex &op2)  { double real  = op1.real()  + op2.real(), imag = op1.imag() + op2.imag(); return(Complex(real, imag)); } c = a+b; c =  operator+  (a, b);
Defined as a friend function Implementing Operator Overloading class Complex { ... public: ... friend Complex operator +( const Complex &,  const Complex & ); ... }; Complex operator +(Complex &op1, Complex &op2)  { double real  = op1._real  + op2._real, imag = op1._imag + op2._imag; return(Complex(real, imag)); } c = a+b; c =  operator+  (a, b);
Ordinary Member Functions, Static Functions and Friend Functions The function can access the private part of the class definition The function is in the scope of the class The function must be invoked on an object Which of these are true about the different functions?
What is ‘Friend’? Friend declarations introduce extra coupling between classes Once an object is declared as a friend, it has access to all non-public members as if they were public Access is  unidirectional If B is designated as friend of A, B can access A’s non-public members; A cannot access B’s A friend function of a class is defined  outside  of that class's scope
More about ‘Friend’ The major use of friends is   to provide more efficient access to data members than the function call to accommodate operator functions with easy access to private data members Friends can have access to everything, which defeats data hiding, so use them carefully Friends have permission to change the internal state from outside the class. Always recommend use member functions instead of friends to change state
Assignment Operator Assignment between objects of the same type is always supported the compiler supplies a hidden assignment function if you don’t write your own one same problem as with the copy constructor - the member by member copying Syntax:  class &  class ::operator=(const  class  &arg)  {     //
 }
Example: Assignment for CStr class CStr& CStr::operator=(const CStr &source){ //... Do the copying return *this; } Assignment operator for CStr: CStr&  CStr::operator=(const CStr & source) Copy Assignment is  different  from Copy Constructor Return type - a reference to (address of) a CStr object Argument type - a reference to a CStr object (since it is const, the function cannot modify it) Assignment function is called as a member function of the left operand =>Return the object itself str1=str2; str1.operator=(str2)
The “ this ” pointer  Within a member function, the  this  keyword is a pointer to the current object, i.e. the object through which the function was called C++ passes a  hidden   this  pointer whenever a member function is called Within a member function definition, there is an implicit use of  this   pointer for references to data members pData nLength this Data member reference Equivalent to pData this->pData nLength this->nLength CStr object (*this)
Overloading stream-insertion and stream-extraction operators In fact, cout<< or cin>> are operator overloading built in C++ standard lib of iostream.h, using operator &quot;<<&quot; and &quot;>>&quot; cout and cin are the objects of ostream and istream classes, respectively We can add a  friend  function which overloads the operator << friend ostream& operator<< (ostream &os, const Date &d); ostream& operator<<(ostream &os, const Date &d) { os<<d.month<<“/”<<d.day<<“/”<<d.year; return os; } 
 cout<< d1;  //overloaded operator ostream& operator<<(ostream &os, const Date &d) { os<<d.month<<“/”<<d.day<<“/”<<d.year; return os; } 
 cout<< d1;  //overloaded operator cout  ----  object of  ostream cout  ----  object of  ostream
Overloading stream-insertion and stream-extraction operators We can also add a  friend  function which overloads the operator >> istream& operator>> (istream &in, Date &d)  { char mmddyy[9]; in >> mmddyy; // check if valid data entered if (d.set(mmddyy))  return in; cout<< &quot;Invalid date format: &quot;<<d<<endl; exit(-1); } friend istream& operator>> (istream &in, Date &d); cin >> d1; cin  ----  object of  istream
Inline functions An inline function is one in which the  function code  replaces the  function call  directly. Inline class member functions   if they are defined as part of the class definition,  implicit if they are defined outside of the class definition,  explicit , I.e.using the keyword,  inline .  Inline functions should be short (preferable one-liners).  Why? Because the use of inline function results in duplication of the code of the function for each invocation of the inline function  
class CStr { char *pData; int nLength; 
 public:   
 char *get_Data(void) {return pData; }//implicit inline function int getlength(void); 
 }; inline  void CStr::getlength(void) //explicit inline function { return nLength; } 
   int main(void) { char *s; int n; CStr a(“Joe”); s = a.get_Data(); n = b.getlength(); }  Example of Inline functions  Inline functions within class declarations Inline functions outside of class declarations In both cases, the compiler will insert the code of the functions get_Data() and getlength() instead of generating calls to these functions
Inline functions (II) An inline function can never be located in a run-time library since the actual code is inserted by the compiler and must therefore be known at  compile-time .   It is only useful to implement an inline function when the time which is spent during a function call is long compared to the code in the function.
Take Home Message Operator overloading provides convenient notations for object behaviors There are three ways to implement operator overloading member functions normal non-member functions friend functions

More Related Content

PPT
14 operator overloading
Docent Education
 
PDF
Operator overloading in C++
Ilio Catallo
 
PPTX
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
PPTX
Operator Overloading
Dustin Chase
 
PPT
Operator overloading
Northeastern University
 
PPTX
Operator overloading and type conversion in cpp
rajshreemuthiah
 
PPT
Overloading
poonamchopra7975
 
PPTX
operator overloading
Sorath Peetamber
 
14 operator overloading
Docent Education
 
Operator overloading in C++
Ilio Catallo
 
Operator Overloading & Type Conversions
Rokonuzzaman Rony
 
Operator Overloading
Dustin Chase
 
Operator overloading
Northeastern University
 
Operator overloading and type conversion in cpp
rajshreemuthiah
 
Overloading
poonamchopra7975
 
operator overloading
Sorath Peetamber
 

What's hot (20)

PPT
Operator overloading
piyush Kumar Sharma
 
PPT
Operator Overloading
Nilesh Dalvi
 
PPTX
Operator overloading
Burhan Ahmed
 
PPTX
Operator overloading
Ramish Suleman
 
PPTX
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
PPTX
Operator overloading
Garima Singh Makhija
 
PPT
Operator overloading in C++
BalajiGovindan5
 
PDF
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
PPTX
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
PPTX
Operator overloading
ramya marichamy
 
PDF
Operator overloading
Pranali Chaudhari
 
PPTX
Bca 2nd sem u-4 operator overloading
Rai University
 
PPTX
operator overloading
Nishant Joshi
 
PPT
C++ overloading
sanya6900
 
PPT
Operator overloading
abhay singh
 
PPTX
Operator overloading
Kumar
 
PPTX
Presentation on overloading
Charndeep Sekhon
 
PPT
08 c++ Operator Overloading.ppt
Tareq Hasan
 
PPTX
Operator overloading and type conversions
Amogh Kalyanshetti
 
Operator overloading
piyush Kumar Sharma
 
Operator Overloading
Nilesh Dalvi
 
Operator overloading
Burhan Ahmed
 
Operator overloading
Ramish Suleman
 
operator overloading & type conversion in cpp over view || c++
gourav kottawar
 
Operator overloading
Garima Singh Makhija
 
Operator overloading in C++
BalajiGovindan5
 
C++ and OOPS Crash Course by ACM DBIT | Grejo Joby
GrejoJoby1
 
#OOP_D_ITS - 5th - C++ Oop Operator Overloading
Hadziq Fabroyir
 
Operator overloading
ramya marichamy
 
Operator overloading
Pranali Chaudhari
 
Bca 2nd sem u-4 operator overloading
Rai University
 
operator overloading
Nishant Joshi
 
C++ overloading
sanya6900
 
Operator overloading
abhay singh
 
Operator overloading
Kumar
 
Presentation on overloading
Charndeep Sekhon
 
08 c++ Operator Overloading.ppt
Tareq Hasan
 
Operator overloading and type conversions
Amogh Kalyanshetti
 
Ad

Viewers also liked (20)

PPTX
Friend function & friend class
Abhishek Wadhwa
 
PPTX
C++ Constructor destructor
Da Mystic Sadi
 
PDF
The State of Twitter: STL 2011
Infuz
 
PDF
STL Algorithms In Action
Northwest C++ Users' Group
 
PPT
Set Theory In C++
Yan (Andrew) Zhuang
 
PPTX
4. Recursion - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
widespreadpromotion
 
PPTX
8. Graph - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
7. Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPT
standard template library(STL) in C++
‱sreejith ‱sree
 
PPTX
5. Queue - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPT
friend function(c++)
Ritika Sharma
 
PPTX
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PPTX
6. Linked list - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
PDF
Đ„Đ°ĐœŃ ЀрДЎрОĐș БДрг - NOARK : ĐĐŸŃ€ĐČДжсĐșĐžĐč ŃŃ‚Đ°ĐœĐŽĐ°Ń€Ń‚ упраĐČĐ»Đ”ĐœĐžŃ ĐŽĐŸĐșŃƒĐŒĐ”ĐœŃ‚Đ°ĐŒĐž
Natasha Khramtsovsky
 
PPTX
PROEXPOSURE spotlight: Yenenesh Abraham
PROEXPOSURE CIC
 
PDF
InterPARES 2: ĐĄĐžŃŃ‚Đ”ĐŒĐ° ĐżŃ€ĐžĐœŃ†ĐžĐżĐŸĐČ ĐŽĐ»Ń Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐž ĐżĐŸĐ»ĐžŃ‚ĐžĐș, стратДгОĐč Đž ŃŃ‚Đ°ĐœĐŽĐ°Ń€Ń‚ĐŸ...
Natasha Khramtsovsky
 
PDF
ĐœĐ”Đ¶ĐŽŃƒĐœĐ°Ń€ĐŸĐŽĐœŃ‹Đ” ŃŃ‚Đ°ĐœĐŽĐ°Ń€Ń‚Ń‹ Ń„ŃƒĐœĐșŃ†ĐžĐŸĐœĐ°Đ»ŃŒĐœŃ‹Ń… Ń‚Ń€Đ”Đ±ĐŸĐČĐ°ĐœĐžĐč Đș ŃĐžŃŃ‚Đ”ĐŒĐ°ĐŒ ŃĐ»Đ”ĐșŃ‚Ń€ĐŸĐœĐœĐŸĐłĐŸ ĐŽĐŸĐș...
Natasha Khramtsovsky
 
PPT
Fys presentation 12_aug_2010
Bruce Gilbert
 
Friend function & friend class
Abhishek Wadhwa
 
C++ Constructor destructor
Da Mystic Sadi
 
The State of Twitter: STL 2011
Infuz
 
STL Algorithms In Action
Northwest C++ Users' Group
 
Set Theory In C++
Yan (Andrew) Zhuang
 
4. Recursion - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
2. Linear Data Structure Using Arrays - Data Structures using C++ by Varsha P...
widespreadpromotion
 
8. Graph - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
7. Tree - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
standard template library(STL) in C++
‱sreejith ‱sree
 
5. Queue - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
friend function(c++)
Ritika Sharma
 
1. Fundamental Concept - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
6. Linked list - Data Structures using C++ by Varsha Patil
widespreadpromotion
 
Đ„Đ°ĐœŃ ЀрДЎрОĐș БДрг - NOARK : ĐĐŸŃ€ĐČДжсĐșĐžĐč ŃŃ‚Đ°ĐœĐŽĐ°Ń€Ń‚ упраĐČĐ»Đ”ĐœĐžŃ ĐŽĐŸĐșŃƒĐŒĐ”ĐœŃ‚Đ°ĐŒĐž
Natasha Khramtsovsky
 
PROEXPOSURE spotlight: Yenenesh Abraham
PROEXPOSURE CIC
 
InterPARES 2: ĐĄĐžŃŃ‚Đ”ĐŒĐ° ĐżŃ€ĐžĐœŃ†ĐžĐżĐŸĐČ ĐŽĐ»Ń Ń€Đ°Đ·Ń€Đ°Đ±ĐŸŃ‚ĐșĐž ĐżĐŸĐ»ĐžŃ‚ĐžĐș, стратДгОĐč Đž ŃŃ‚Đ°ĐœĐŽĐ°Ń€Ń‚ĐŸ...
Natasha Khramtsovsky
 
ĐœĐ”Đ¶ĐŽŃƒĐœĐ°Ń€ĐŸĐŽĐœŃ‹Đ” ŃŃ‚Đ°ĐœĐŽĐ°Ń€Ń‚Ń‹ Ń„ŃƒĐœĐșŃ†ĐžĐŸĐœĐ°Đ»ŃŒĐœŃ‹Ń… Ń‚Ń€Đ”Đ±ĐŸĐČĐ°ĐœĐžĐč Đș ŃĐžŃŃ‚Đ”ĐŒĐ°ĐŒ ŃĐ»Đ”ĐșŃ‚Ń€ĐŸĐœĐœĐŸĐłĐŸ ĐŽĐŸĐș...
Natasha Khramtsovsky
 
Fys presentation 12_aug_2010
Bruce Gilbert
 
Ad

Similar to Lecture5 (20)

PPT
Lecture5
Sunil Gupta
 
PDF
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
PPT
Memory Management In C++
ShriKant Vashishtha
 
PPT
C++ Function
Hajar
 
PPT
Presentation
manogallery
 
PDF
02.adt
Aditya Asmara
 
PPT
Virtual Function and Polymorphism.ppt
ishan743441
 
PPTX
C++ language
Hamza Asif
 
PDF
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
PDF
overloading in C++
Prof Ansari
 
PPT
An imperative study of c
Tushar B Kute
 
PPTX
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
PPTX
C++ theory
Shyam Khant
 
PPT
C++ tutorials
Divyanshu Dubey
 
PPT
C++ Advanced
Vivek Das
 
PPT
Clean code _v2003
R696
 
PPTX
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
DOCX
New microsoft office word document (2)
rashmita_mishra
 
PDF
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
PPTX
Operator overloading2
zindadili
 
Lecture5
Sunil Gupta
 
22 scheme OOPs with C++ BCS306B_module2.pdfmodule2.pdf
sindhus795217
 
Memory Management In C++
ShriKant Vashishtha
 
C++ Function
Hajar
 
Presentation
manogallery
 
02.adt
Aditya Asmara
 
Virtual Function and Polymorphism.ppt
ishan743441
 
C++ language
Hamza Asif
 
Basics _of_Operator Overloading_Somesh_Kumar_SSTC
drsomeshdewangan
 
overloading in C++
Prof Ansari
 
An imperative study of c
Tushar B Kute
 
Object Oriented Programming using C++: Ch08 Operator Overloading.pptx
RashidFaridChishti
 
C++ theory
Shyam Khant
 
C++ tutorials
Divyanshu Dubey
 
C++ Advanced
Vivek Das
 
Clean code _v2003
R696
 
Chapter 2 OOP using C++ (Introduction).pptx
FiraolGadissa
 
New microsoft office word document (2)
rashmita_mishra
 
Object Oriented Programming (OOP) using C++ - Lecture 1
Faculty of Computers and Informatics, Suez Canal University, Ismailia, Egypt
 
Operator overloading2
zindadili
 

Recently uploaded (20)

PDF
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
REPORT: Heating appliances market in Poland 2024
SPIUG
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
PDF
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
PPTX
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
PDF
Software Development Company | KodekX
KodekX
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PDF
DevOps & Developer Experience Summer BBQ
AUGNYC
 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
PDF
Software Development Methodologies in 2025
KodekX
 
PDF
Orbitly Pitch DeckA Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
PDF
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
PDF
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java ‱ Spring Boot ‱ Ka...
SHREYAS PHANSE
 
PPTX
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
PDF
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
PPTX
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 
Revolutionize Operations with Intelligent IoT Monitoring and Control
Rejig Digital
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
REPORT: Heating appliances market in Poland 2024
SPIUG
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
A Day in the Life of Location Data - Turning Where into How.pdf
Precisely
 
Enable Enterprise-Ready Security on IBM i Systems.pdf
Precisely
 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
 
C Programming Basics concept krnppt.pptx
Karan Prajapat
 
Software Development Company | KodekX
KodekX
 
This slide provides an overview Technology
mineshkharadi333
 
DevOps & Developer Experience Summer BBQ
AUGNYC
 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
 
Software Development Methodologies in 2025
KodekX
 
Orbitly Pitch DeckA Mission-Driven Platform for Side Project Collaboration (...
zz41354899
 
Using Anchore and DefectDojo to Stand Up Your DevSecOps Function
Anchore
 
Shreyas_Phanse_Resume: Experienced Backend Engineer | Java ‱ Spring Boot ‱ Ka...
SHREYAS PHANSE
 
PA Analog/Digital System: The Backbone of Modern Surveillance and Communication
AVTRON Technologies LLC
 
Chapter 2 Digital Image Fundamentals.pdf
Getnet Tigabie Askale -(GM)
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
Comunidade Salesforce SĂŁo Paulo - Desmistificando o Omnistudio (Vlocity)
Francisco Vieira JĂșnior
 

Lecture5

  • 1. More C++ Concepts Operator overloading Friend Function This Operator Inline Function
  • 2. Operator overloading Programmer can use some operator symbols to define special member functions of a class Provides convenient notations for object behaviors
  • 3. Why Operator Overloading int i, j, k; // integers float m, n, p; // floats k = i + j; // integer addition and assignment p = m + n; // floating addition and assignment The compiler overloads the + operator for built-in integer and float types by default, producing integer addition with i+j, and floating addition with m+n. We can make object operation look like individual int variable operation, using operator functions Complex a,b,c; c = a + b;
  • 4. Operator Overloading Syntax Syntax is: operator @(argument-list) --- operator is a function --- @ is one of C++ operator symbols (+, -, =, etc..) Examples: operator+ operator- operator* operator/
  • 5. class CStr { char *pData; int nLength; public: // 
 void cat(char *s); // 
 CStr operator+ (CStr str1, CStr str2); CStr operator+ (CStr str, char *s); CStr operator+ (char *s, CStr str); //accessors char* get_Data(); int get_Len(); }; Example of Operator Overloading void CStr::cat(char *s) { int n; char *pTemp; n=strlen(s); if (n==0) return; pTemp=new char[n+nLength+1]; if (pData) strcpy(pTemp,pData); strcat(pTemp,s); pData=pTemp; nLength+=n; }
  • 6. The Addition (+) Operator CStr CStr::operator+(CStr str1, CStr str2) { CStr new_string(str1); //call the copy constructor to initialize an //entirely new CStr object with the first //operand new_string.cat(str2.get_Data()); //concatenate the second operand onto the //end of new_string return new_string; //call copy constructor to create a copy of //the return value new_string } new_string str1 strlen(str1) strcat(str1,str2) strlen(str1)+strlen(str2)
  • 7. How does it work? CStr first(“John”); CStr last(“Johnson”); CStr name(first+last); CStr CStr::operator+ (CStr str1,CStr str2) { CStr new_string(str1); new_string.cat(str2.get()); return new_string; } “ John Johnson” Temporary CStr object Copy constructor name
  • 8. Implementing Operator Overloading Two ways: Implemented as member functions Implemented as non-member or Friend functions the operator function may need to be declared as a friend if it requires access to protected or private data Expression [email_address] translates into a function call obj1.operator@(obj2) , if this function is defined within class obj1 operator@(obj1,obj2) , if this function is defined outside the class obj1
  • 9. Defined as a member function Implementing Operator Overloading class Complex { ... public: ... Complex operator +(const Complex &op) { double real = _real + op._real, imag = _imag + op._imag; return(Complex(real, imag)); } ... }; c = a+b; c = a.operator+ (b);
  • 10. Defined as a non-member function Implementing Operator Overloading class Complex { ... public: ... double real() { return _real; } //need access functions double imag() { return _imag; } ... }; Complex operator +(Complex &op1, Complex &op2) { double real = op1.real() + op2.real(), imag = op1.imag() + op2.imag(); return(Complex(real, imag)); } c = a+b; c = operator+ (a, b);
  • 11. Defined as a friend function Implementing Operator Overloading class Complex { ... public: ... friend Complex operator +( const Complex &, const Complex & ); ... }; Complex operator +(Complex &op1, Complex &op2) { double real = op1._real + op2._real, imag = op1._imag + op2._imag; return(Complex(real, imag)); } c = a+b; c = operator+ (a, b);
  • 12. Ordinary Member Functions, Static Functions and Friend Functions The function can access the private part of the class definition The function is in the scope of the class The function must be invoked on an object Which of these are true about the different functions?
  • 13. What is ‘Friend’? Friend declarations introduce extra coupling between classes Once an object is declared as a friend, it has access to all non-public members as if they were public Access is unidirectional If B is designated as friend of A, B can access A’s non-public members; A cannot access B’s A friend function of a class is defined outside of that class's scope
  • 14. More about ‘Friend’ The major use of friends is to provide more efficient access to data members than the function call to accommodate operator functions with easy access to private data members Friends can have access to everything, which defeats data hiding, so use them carefully Friends have permission to change the internal state from outside the class. Always recommend use member functions instead of friends to change state
  • 15. Assignment Operator Assignment between objects of the same type is always supported the compiler supplies a hidden assignment function if you don’t write your own one same problem as with the copy constructor - the member by member copying Syntax: class & class ::operator=(const class &arg) { //
 }
  • 16. Example: Assignment for CStr class CStr& CStr::operator=(const CStr &source){ //... Do the copying return *this; } Assignment operator for CStr: CStr& CStr::operator=(const CStr & source) Copy Assignment is different from Copy Constructor Return type - a reference to (address of) a CStr object Argument type - a reference to a CStr object (since it is const, the function cannot modify it) Assignment function is called as a member function of the left operand =>Return the object itself str1=str2; str1.operator=(str2)
  • 17. The “ this ” pointer Within a member function, the this keyword is a pointer to the current object, i.e. the object through which the function was called C++ passes a hidden this pointer whenever a member function is called Within a member function definition, there is an implicit use of this pointer for references to data members pData nLength this Data member reference Equivalent to pData this->pData nLength this->nLength CStr object (*this)
  • 18. Overloading stream-insertion and stream-extraction operators In fact, cout<< or cin>> are operator overloading built in C++ standard lib of iostream.h, using operator &quot;<<&quot; and &quot;>>&quot; cout and cin are the objects of ostream and istream classes, respectively We can add a friend function which overloads the operator << friend ostream& operator<< (ostream &os, const Date &d); ostream& operator<<(ostream &os, const Date &d) { os<<d.month<<“/”<<d.day<<“/”<<d.year; return os; } 
 cout<< d1; //overloaded operator ostream& operator<<(ostream &os, const Date &d) { os<<d.month<<“/”<<d.day<<“/”<<d.year; return os; } 
 cout<< d1; //overloaded operator cout ---- object of ostream cout ---- object of ostream
  • 19. Overloading stream-insertion and stream-extraction operators We can also add a friend function which overloads the operator >> istream& operator>> (istream &in, Date &d) { char mmddyy[9]; in >> mmddyy; // check if valid data entered if (d.set(mmddyy)) return in; cout<< &quot;Invalid date format: &quot;<<d<<endl; exit(-1); } friend istream& operator>> (istream &in, Date &d); cin >> d1; cin ---- object of istream
  • 20. Inline functions An inline function is one in which the function code replaces the function call directly. Inline class member functions if they are defined as part of the class definition, implicit if they are defined outside of the class definition, explicit , I.e.using the keyword, inline . Inline functions should be short (preferable one-liners). Why? Because the use of inline function results in duplication of the code of the function for each invocation of the inline function  
  • 21. class CStr { char *pData; int nLength; 
 public: 
 char *get_Data(void) {return pData; }//implicit inline function int getlength(void); 
 }; inline void CStr::getlength(void) //explicit inline function { return nLength; } 
   int main(void) { char *s; int n; CStr a(“Joe”); s = a.get_Data(); n = b.getlength(); } Example of Inline functions Inline functions within class declarations Inline functions outside of class declarations In both cases, the compiler will insert the code of the functions get_Data() and getlength() instead of generating calls to these functions
  • 22. Inline functions (II) An inline function can never be located in a run-time library since the actual code is inserted by the compiler and must therefore be known at compile-time . It is only useful to implement an inline function when the time which is spent during a function call is long compared to the code in the function.
  • 23. Take Home Message Operator overloading provides convenient notations for object behaviors There are three ways to implement operator overloading member functions normal non-member functions friend functions