Chapter 17: Advanced C++ Topics I

Chapter Goals

Operator Overloading

Operator Functions

Syntax 17.1: Overloading Operator Definition

Syntax 17.1 : Overloading Operator Definition

return_type operatoroperator_symbol(parameters)
{

statements
}
Example:
int operator-(Time a, Time b)
{
return a.seconds_from(b)
}
Purpose: Supply the implementation of an overloaded operator.

Overloading Comparison Operations

  • A commonly overloaded operator is the == operator, to compare two values.
    bool operator==(Time a, Time b)
    { return a.seconds_from(b) == 0;
    }
  • For completeness, it is a good idea to also define a != operator.
    bool operator!=(Time a, Time b)
    { return a.seconds_from(b) != 0;
    }
  • You may also find it useful to define a < operator.
    bool operator<(Time a, Time b)
    { return a.seconds_from(b) < 0;
    }
  • Input and Output

    Operator Overloading (overload.cpp)

    Overloading Increment and Decrement Operators

    Operator Members

    Operator Overloading (overload1.cpp)


    Automatic Memory Management

    Destructors

    Syntax 17.2: Destructor Definition

    Syntax 17.2 : Destructor Definition

    Class_name::~Class_name()
    {

    statements
    }
    Example:
    Department::~Department()
    {
    delete receptionist;
    }
    Purpose: Supply the implementation of a destructor that is invoked whenever and object goes out of scope.

    Overloading the Assignment Operator

    Copy Constructor

    The Big Three

    Automatic Memory Management (department.cpp)