SlideShare a Scribd company logo
1 of 23
More C++ Concepts

• Operator overloading
• Friend Function
• This Operator
• Inline Function



                         1
Operator overloading

• Programmer can use some operator
  symbols to define special member
  functions of a class

• Provides convenient notations for
  object behaviors



                               2
Why Operator Overloading

int i, j, k;     // integers
float m, n, p;   // floats                 The compiler overloads
                                         the + operator for built-in
                                         integer and float types by
k = i + j;                               default, producing integer
   // integer addition and assignment    addition with i+j, and
p = m + n;                               floating addition with m+n.
   // floating addition and assignment


      We can make object operation look like individual
      int variable operation, using operator functions
            Complex a,b,c;
            c = a + b;
                                                     3
Operator Overloading Syntax
• Syntax is:                                 Examples:
                                             operator+

   operator@(argument-list)                  operator-
                                             operator*
                                             operator/
   --- operator is a function

   --- @ is one of C++ operator symbols (+, -, =, etc..)


                                                4
Example of Operator Overloading
class CStr
{
                                             void CStr::cat(char *s)
    char *pData;
                                             {
    int nLength;
                                               int n;
  public:
                                               char *pTemp;
    // …                                       n=strlen(s);
    void cat(char *s);                         if (n==0) return;
    // …
     CStr operator+(CStr str1, CStr str2);       pTemp=new char[n+nLength+1];
     CStr operator+(CStr str, char *s);          if (pData)
     CStr operator+(char *s, CStr str);             strcpy(pTemp,pData);
      //accessors                                strcat(pTemp,s);
     char* get_Data();                           pData=pTemp;
     int get_Len();                              nLength+=n;
                                             }
};
                                                            5
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
                                                          strcat(str1,str2)
                                                          strlen(str1)
                                                          strlen(str1)+strlen(str2
                                                                     6
                                                          )
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;
                }



       name                           “John Johnson”
                   Copy constructor
                                      Temporary CStr object

                                                7
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 obj1@obj2 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

                                                 8
Implementing Operator Overloading

1. Defined as a member function
 class Complex {
    ...
  public:
    ...                                     c = a+b;
    Complex operator +(const Complex &op)
    {
      double real = _real + op._real,       c = a.operator+
             imag = _imag + op._imag;       (b);
      return(Complex(real, imag));
    }
    ...
  };
                                                9
Implementing Operator Overloading

2. Defined as a non-member function
class Complex {
   ...                                       c = a+b;
 public:
   ...
  double real() { return _real; }              c = operator+ (a,
    //need access functions                    b);
  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));
                                                            10
                            }
Implementing Operator Overloading

3. Defined as a friend function
class Complex {
   ...                                     c = a+b;
 public:
   ...
  friend Complex operator +(                 c = operator+ (a,
     const Complex &,                        b);
     const Complex &
   );
                          Complex operator +(Complex &op1, Complex &op2)
   ...
                          {
 };
                             double real = op1._real + op2._real,
                                    imag = op1._imag + op2._imag;
                             return(Complex(real, imag));
                                                          11
                          }
Ordinary Member Functions, Static Functions
            and Friend Functions
1. The function can access the private part
   of the class definition
2. The function is in the scope of the class
3. The function must be invoked on an object

   Which of these are true about the different functions?




                                            12
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
                                      13
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
                                        14
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)
       {
          //…
       }
                                                    15
Example: Assignment for CStr class
               Assignment operator for CStr:
               CStr& CStr::operator=(const CStr & source)
    Return type - a reference to   Argument type - a reference to a CStr object
    (address of) a CStr object     (since it is const, the function cannot modify it)


CStr& CStr::operator=(const CStr &source){
//... Do the copying
return *this;
                                Assignment function is called as a
}
                                         member function of the left operand
                                         =>Return the object itself
     str1=str2;
                                        Copy Assignment is different from
                                        Copy Constructor
     str1.operator=(str2)                                    16
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


  this                           Data member reference      Equivalent to
                 pData           pData                      this->pData
                                 nLength                    this->nLength
                nLength

                CStr object
                  (*this)
                                                       17
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 "<<" and ">>"
• 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 ---- object of ostream
       }
       …
       cout<< d1; //overloaded operator
                                                    18
Overloading stream-insertion and
    stream-extraction operators
• We can also add a friend function which overloads the
  operator >>
 friend istream& operator>> (istream &in, Date &d);

   istream& operator>> (istream &in, Date &d)
   {
     char mmddyy[9];
       in >> mmddyy;                    cin ---- object of istream
       // check if valid data entered
       if (d.set(mmddyy)) return in;
       cout<< "Invalid date format: "<<d<<endl;
       exit(-1);
   }
                                                         cin >> d1;
                                                       19
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
                                         20
Example of Inline functions
class CStr
{
  char *pData;
  int nLength;
     …
  public:               Inline functions within class declarations
     …
    char *get_Data(void) {return pData; }//implicit inline function
    int getlength(void);
     …
};
inline void CStr::getlength(void) //explicit inline function
{
  return nLength;
}                     Inline functions outside of class declarations
    …
int main(void)
{
  char *s;
  int n;
  CStr a(“Joe”);
  s = a.get_Data();
                       In both cases, the compiler will insert the
  n = b.getlength();   code of the functions get_Data() and
}
                       getlength() instead of generating calls to these
                       functions                   21
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.

                                  22
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
                                  23

More Related Content

What's hot

Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Liju Thomas
 
class and objects
class and objectsclass and objects
class and objectsPayel Guria
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++sandeep54552
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introductionsandeep54552
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7kamal kotecha
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritancemanish kumar
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorialsFALLEE31188
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Ameen Sha'arawi
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functionsMarlom46
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructorsPraveen M Jigajinni
 
Variables in python
Variables in pythonVariables in python
Variables in pythonJaya Kumari
 

What's hot (20)

Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++Abstract Base Class and Polymorphism in C++
Abstract Base Class and Polymorphism in C++
 
class and objects
class and objectsclass and objects
class and objects
 
Java interface
Java interfaceJava interface
Java interface
 
Constructor and Destructors in C++
Constructor and Destructors in C++Constructor and Destructors in C++
Constructor and Destructors in C++
 
OOPS Basics With Example
OOPS Basics With ExampleOOPS Basics With Example
OOPS Basics With Example
 
C++ oop
C++ oopC++ oop
C++ oop
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
C++ programming introduction
C++ programming introductionC++ programming introduction
C++ programming introduction
 
Inheritance chepter 7
Inheritance chepter 7Inheritance chepter 7
Inheritance chepter 7
 
Oops
OopsOops
Oops
 
Constructors and destructors
Constructors and destructorsConstructors and destructors
Constructors and destructors
 
Lecture 6 inheritance
Lecture   6 inheritanceLecture   6 inheritance
Lecture 6 inheritance
 
Dynamic method dispatch
Dynamic method dispatchDynamic method dispatch
Dynamic method dispatch
 
C++ classes tutorials
C++ classes tutorialsC++ classes tutorials
C++ classes tutorials
 
Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++Support for Object-Oriented Programming (OOP) in C++
Support for Object-Oriented Programming (OOP) in C++
 
Data members and member functions
Data members and member functionsData members and member functions
Data members and member functions
 
Interface
InterfaceInterface
Interface
 
Chapter 06 constructors and destructors
Chapter 06 constructors and destructorsChapter 06 constructors and destructors
Chapter 06 constructors and destructors
 
Variables in python
Variables in pythonVariables in python
Variables in python
 

Viewers also liked

#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
 
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Abu Saleh
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Jenish Patel
 
02. functions & introduction to class
02. functions & introduction to class02. functions & introduction to class
02. functions & introduction to classHaresh Jaiswal
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programmingnirajmandaliya
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadngpreethalal
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++Ilio Catallo
 
Friend functions
Friend functions Friend functions
Friend functions Megha Singh
 
Inline function
Inline functionInline function
Inline functionTech_MX
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++Aabha Tiwari
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++Learn By Watch
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++M Hussnain Ali
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member FunctionsMuhammad Hammad Waseem
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend classAbhishek Wadhwa
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++Muhammad Waqas
 
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 OverloadingNilesh Dalvi
 
Classes and objects
Classes and objectsClasses and objects
Classes and objectsNilesh Dalvi
 

Viewers also liked (20)

Best javascript course
Best javascript courseBest javascript course
Best javascript course
 
Lecture05
Lecture05Lecture05
Lecture05
 
#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
 
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15Lecture 5, c++(complete reference,herbet sheidt)chapter-15
Lecture 5, c++(complete reference,herbet sheidt)chapter-15
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
02. functions & introduction to class
02. functions & introduction to class02. functions & introduction to class
02. functions & introduction to class
 
C++ Object oriented concepts & programming
C++ Object oriented concepts & programmingC++ Object oriented concepts & programming
C++ Object oriented concepts & programming
 
Operator overloadng
Operator overloadngOperator overloadng
Operator overloadng
 
Operator overloading in C++
Operator overloading in C++Operator overloading in C++
Operator overloading in C++
 
Friend functions
Friend functions Friend functions
Friend functions
 
Inline function
Inline functionInline function
Inline function
 
OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++OPERATOR OVERLOADING IN C++
OPERATOR OVERLOADING IN C++
 
Inline function in C++
Inline function in C++Inline function in C++
Inline function in C++
 
A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++A COMPLETE FILE FOR C++
A COMPLETE FILE FOR C++
 
[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions[OOP - Lec 19] Static Member Functions
[OOP - Lec 19] Static Member Functions
 
Friend function & friend class
Friend function & friend classFriend function & friend class
Friend function & friend class
 
Object Oriented Programming Using C++
Object Oriented Programming Using C++Object Oriented Programming Using C++
Object Oriented Programming Using C++
 
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
 
Classes and objects
Classes and objectsClasses and objects
Classes and objects
 

Similar to Lecture5

Similar to Lecture5 (20)

Lecture5
Lecture5Lecture5
Lecture5
 
Overloading
OverloadingOverloading
Overloading
 
Operator overloading2
Operator overloading2Operator overloading2
Operator overloading2
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Ch-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdfCh-4-Operator Overloading.pdf
Ch-4-Operator Overloading.pdf
 
Operator overload rr
Operator overload  rrOperator overload  rr
Operator overload rr
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
Ds lab handouts
Ds lab handoutsDs lab handouts
Ds lab handouts
 
Lecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handlingLecture05 operator overloading-and_exception_handling
Lecture05 operator overloading-and_exception_handling
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Mca 2nd sem u-2 classes & objects
Mca 2nd  sem u-2 classes & objectsMca 2nd  sem u-2 classes & objects
Mca 2nd sem u-2 classes & objects
 
Bca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objectsBca 2nd sem u-2 classes & objects
Bca 2nd sem u-2 classes & objects
 
Review constdestr
Review constdestrReview constdestr
Review constdestr
 
C++_notes.pdf
C++_notes.pdfC++_notes.pdf
C++_notes.pdf
 
Functional Programming
Functional ProgrammingFunctional Programming
Functional Programming
 
Introduction to c ++ part -2
Introduction to c ++   part -2Introduction to c ++   part -2
Introduction to c ++ part -2
 
C++ process new
C++ process newC++ process new
C++ process new
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 
Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)Operator_Overloaing_Type_Conversion_OOPC(C++)
Operator_Overloaing_Type_Conversion_OOPC(C++)
 

Recently uploaded

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991RKavithamani
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdfssuser54595a
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 

Recently uploaded (20)

Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
Industrial Policy - 1948, 1956, 1973, 1977, 1980, 1991
 
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
Mattingly "AI & Prompt Design: Structured Data, Assistants, & RAG"
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
18-04-UA_REPORT_MEDIALITERAСY_INDEX-DM_23-1-final-eng.pdf
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 

Lecture5

  • 1. More C++ Concepts • Operator overloading • Friend Function • This Operator • Inline Function 1
  • 2. Operator overloading • Programmer can use some operator symbols to define special member functions of a class • Provides convenient notations for object behaviors 2
  • 3. Why Operator Overloading int i, j, k; // integers float m, n, p; // floats The compiler overloads the + operator for built-in integer and float types by k = i + j; default, producing integer // integer addition and assignment addition with i+j, and p = m + n; floating addition with m+n. // floating addition and assignment We can make object operation look like individual int variable operation, using operator functions Complex a,b,c; c = a + b; 3
  • 4. Operator Overloading Syntax • Syntax is: Examples: operator+ operator@(argument-list) operator- operator* operator/ --- operator is a function --- @ is one of C++ operator symbols (+, -, =, etc..) 4
  • 5. Example of Operator Overloading class CStr { void CStr::cat(char *s) char *pData; { int nLength; int n; public: char *pTemp; // … n=strlen(s); void cat(char *s); if (n==0) return; // … CStr operator+(CStr str1, CStr str2); pTemp=new char[n+nLength+1]; CStr operator+(CStr str, char *s); if (pData) CStr operator+(char *s, CStr str); strcpy(pTemp,pData); //accessors strcat(pTemp,s); char* get_Data(); pData=pTemp; int get_Len(); nLength+=n; } }; 5
  • 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 strcat(str1,str2) strlen(str1) strlen(str1)+strlen(str2 6 )
  • 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; } name “John Johnson” Copy constructor Temporary CStr object 7
  • 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 obj1@obj2 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 8
  • 9. Implementing Operator Overloading 1. Defined as a member function class Complex { ... public: ... c = a+b; Complex operator +(const Complex &op) { double real = _real + op._real, c = a.operator+ imag = _imag + op._imag; (b); return(Complex(real, imag)); } ... }; 9
  • 10. Implementing Operator Overloading 2. Defined as a non-member function class Complex { ... c = a+b; public: ... double real() { return _real; } c = operator+ (a, //need access functions b); 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)); 10 }
  • 11. Implementing Operator Overloading 3. Defined as a friend function class Complex { ... c = a+b; public: ... friend Complex operator +( c = operator+ (a, const Complex &, b); const Complex & ); Complex operator +(Complex &op1, Complex &op2) ... { }; double real = op1._real + op2._real, imag = op1._imag + op2._imag; return(Complex(real, imag)); 11 }
  • 12. Ordinary Member Functions, Static Functions and Friend Functions 1. The function can access the private part of the class definition 2. The function is in the scope of the class 3. The function must be invoked on an object Which of these are true about the different functions? 12
  • 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 13
  • 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 14
  • 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) { //… } 15
  • 16. Example: Assignment for CStr class Assignment operator for CStr: CStr& CStr::operator=(const CStr & source) Return type - a reference to Argument type - a reference to a CStr object (address of) a CStr object (since it is const, the function cannot modify it) CStr& CStr::operator=(const CStr &source){ //... Do the copying return *this; Assignment function is called as a } member function of the left operand =>Return the object itself str1=str2; Copy Assignment is different from Copy Constructor str1.operator=(str2) 16
  • 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 this Data member reference Equivalent to pData pData this->pData nLength this->nLength nLength CStr object (*this) 17
  • 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 "<<" and ">>" • 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 ---- object of ostream } … cout<< d1; //overloaded operator 18
  • 19. Overloading stream-insertion and stream-extraction operators • We can also add a friend function which overloads the operator >> friend istream& operator>> (istream &in, Date &d); istream& operator>> (istream &in, Date &d) { char mmddyy[9]; in >> mmddyy; cin ---- object of istream // check if valid data entered if (d.set(mmddyy)) return in; cout<< "Invalid date format: "<<d<<endl; exit(-1); } cin >> d1; 19
  • 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 20
  • 21. Example of Inline functions class CStr { char *pData; int nLength; … public: Inline functions within class declarations … char *get_Data(void) {return pData; }//implicit inline function int getlength(void); … }; inline void CStr::getlength(void) //explicit inline function { return nLength; } Inline functions outside of class declarations … int main(void) { char *s; int n; CStr a(“Joe”); s = a.get_Data(); In both cases, the compiler will insert the n = b.getlength(); code of the functions get_Data() and } getlength() instead of generating calls to these functions 21
  • 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. 22
  • 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 23