Overloading Operators Using Member Functions

Introduction

When overloading an operator using a member function:

  • The leftmost operand of the overloaded operator must be an object of the class type.
  • The leftmost operand becomes the implicit *this * parameter. All other operands become function parameters.

Overloading the unary negative (-) operator

Example 1: Using a friend function

class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Overload -cCents
    friend Cents operator-(const Cents &cCents);
};
 
// note: this function is not a member function!
Cents operator-(const Cents &cCents)
{
    return Cents(-cCents.m_nCents);
}

Example 2: Using a member function

class Cents
{
private:
    int m_nCents;
 
public:
    Cents(int nCents) { m_nCents = nCents; }
 
    // Overload -cCents
    Cents operator-();
};
 
// note: this function is a member function!
Cents Cents::operator-()
{
    return Cents(-m_nCents);
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-Share Alike 2.5 License.