Operator Overloading - PowerPoint PPT Presentation

About This Presentation
Title:

Operator Overloading

Description:

Operator Overloading Syntax The general syntax is: [friend] returntype operator ( ) { ; } Syntax The number of arguments ... – PowerPoint PPT presentation

Number of Views:107
Avg rating:3.0/5.0
Slides: 10
Provided by: RobinS208
Category:

less

Transcript and Presenter's Notes

Title: Operator Overloading


1
Operator Overloading
2
Syntax
  • The general syntax is
  • friend returntype operatorltoperator symbolgt
  • ( ltparametersgt )
  • ltstatementsgt

3
Syntax
  • The number of arguments in the overloaded
    operators argument list depends on two factors
  • Whether its a unary operator (one argument) or a
    binary operator (two arguments).
  • Whether the operator is defined as a global
    function (one argument for unary, two for binary)
    or a member function (zero arguments for unary,
    one for binary the object becomes the left-hand
    argument).

4
Operators that cant be overloaded
  • All operators can be overloaded except for the
    ones below
  • The member selection operator - .
  • The pointer to member dereference operator - .
  • Scope access/resolution operator -
  • Conditional operator - ?
  • Also, there are no user-defined operators and you
    cant change the precedence rules.

5
Overloaded operators as member or non-member
functions?
  • The decision is based on what argument(s) is
    needed by the operator.
  • In general, if it doesnt make any difference,
    they should be members, to emphasize the
    association between the operator and its class.
  • When the left-hand operand is always an object of
    the current class, this works fine.
  • Sometimes you want the left-hand operand to be an
    object of some other class, then the overloaded
    operator cannot be a member function.

6
Some tricky operators
  • Increment and decrement operators
  • a (a pre-increment) generates a call to
    operator(a)
  • a (a post-increment) generates a call to
    operator(a,int)for non-member functions.
  • The member function versions, would be
  • Boperator( ) and
  • Boperator(int)
  • Note a dummy value is passed by the compiler to
    distinguish (generate different signatures) the
    two versions.

7
Some tricky operators
  • The assignment operator
  • Defining the assignment operator has a lot in
    common with defining the copy constructor and the
    destructor.
  • List Listoperator( const List b )
  • if( this ! b) //check for self assignment
  • free()
  • copy(b)
  • return this

8
An example
  • Lets look at our example implementation of the
    class Values

9
Arguments and return values
  • Guidelines
  • Return by value as const
  • The return value optimization
Write a Comment
User Comments (0)
About PowerShow.com