12. Operator Overloading

About this Tutorial –

Objectives –

This course is aimed at students who need to get up to speed in C++. The course introduces object-oriented concepts and shows how they are implemented in C++. The course does not require awareness or familiarity with object-oriented programming techniques, but programming experience would be useful but not necessarily required.

Audience

Students who are new to object orientation (or programming) and need to learn C++.

Prerequisites

No previous experience in C++ programming is required. But any experience you do have in programming will help. Also no experience in Visual Studio is required. But again any experience you do have with programming development environments will be a valuable.

Contents

The C++ course covers these topics and more:

  • Introduction to C++: Key features of C++; Defining variables; Formulating expressions and statements; Built-in data types; Console input/output
  • Operators and types: Assignment; Compound Assignment; Increment and decrement operators; Const declarations; Type conversions
  • Going Further with Data Types: Enumerations; Arrays; Using the standard vector class; Using the standard string class; Structures

Download Solutions

Java tutorial


Overview

Estimated Time – 0.5 Hours

Not what you are looking? Try the next tutorial – Copying and Assignment

Lab 1: Key concepts

Lab 1: Key concepts
  1. Overview of Operator Operloading
    • Support for operators in C++:
      • For built-in types, operators are supported intrinsically
      • For user-defined types, operators are NOT supported intrinsically
        // Good
        int a, b;
        int sum = a + b;
        int diff = a - b;
        int half = a / 2;
        a++;
        --b;
        if (a == b) ...
        if (a >= b) ...
        //Bad
        Money a, b;
        Money sum = a + b;
        Money diff = a - b;
        Money half = a / 2;
        a++;
        --b;
        if (a == b) ...
        if (a >= b) ...
    • However, you can define operator functions in classes
      • To add support for operators for your classes
      • You can support most existing operators (can’t invent new ones!)
  2. Types of Operators
    • There are two types of operator that you can override…
    • Unary operators
      • Just take the class object as the single operand
      • For example:
        a++
        --a
        -a
        !a
    • Binary operators
      • Take two operands
      • The class object, plus another operand
      • For example:
        a + b
        a - b
        a == b
        a != b
  3. Operator Function Syntax
    • General syntax for defining an operator function:
      • Number of parambers depends on whether it’s unary/binary
      • Return type must be consistent with operator for built-in types
        return_type operator operator_symbol(parameters)
Lab
  1. Defining basic Time and Timespan types
    • In Visual Studio, create a new C++ project named OperatorOverloadingApp in the student folder.
    • Define a class named Time as follows:
      • The class should store a time of day internally as a single integer, i.e. seconds-since-midnight.
      • Define a constructor to initialize a Time from hours, minutes, and seconds, to allow the client to create objects such as Time(23, 59, 59). Make appropriate use of default arguments, to allow some flexibility here
        Time::Time(int h, int m, int s)
        {
         Set(h, m, s);
        }
      • Make appropriate use of default arguments to allow some flexibility here
      • Add other methods you think might be useful. Keep it simple though!
        void Time::Set(int h, int m, int s)
        {
         seconds = h * 3600 + m * 60 + s;
        }
        int Time::GetHour() const
        {
         return seconds / 3600;
        }
        int Time::GetMinute() const
        {
         int secondsInFullHours = GetHour() * 3600;
         int additionalSeconds = seconds - secondsInFullHours;
         return additionalSeconds / 60;
        }
        int Time::GetSecond() const
        {
         return seconds % 60;
        }
        string Time::ToString() const
        {
         stringstream stm;
         stm << GetHour() << ":" << GetMinute() << ":" << GetSecond();  return stm.str(); }
      • View code file.
    • Define a typedef named Timespan, which represents an integer
      typedef int Timespan;

Lab 2: Unary operators

Lab 2: Unary operators
  1. Overview of Unary Operators
    • Unary operators take a single operand
      • i.e. the object itself
    • To implement a unary operator:
      • Define as a member function, with no explicit parameters
      • The implicit this parameter identifies the target object
  2. Defining Unary Operators
    • To define unary operators:
      class Money
      {
      private:
       int dollars, cents;
      public:
       Money operator-() const;  // Unary negation
       bool operator!() const;  // Unary not
       ...
      };
    • To implement unary operators:
      Money Money::operator-() const
      {
       return Money(-dollars, cents);
      }
      bool Money::operator!() const
      {
       return (dollars == 0 && cents == 0);
      }
  3. Using Unary Operators
    • Client code can use unary operators as follows:
      Money money1(10, 20);
      Money money2;
      // The following two statements are equivalent:
      money2 = -money1;
      money2 = money1.operator-();
      // The following two statements are equivalent:
      if (!money1) ...
      if (money1.operator!()) ...
  4. A Special Word about ++ and --
    • The ++ and -- unary operators are special...
      • They can be used in prefix or postfix position
      • By definition, this is how you implement ++ (ditto for --):
        // Header
        class Money
        {
        public:
         Money& operator++();    // Prefix
         Money operator++(int);   // Postfix
         ...
        // Cpp File
        Money& Money::operator++()
        {
         dollars++;
         return *this;
        }
        Money Money::operator++(int)
        {
         Money orig = *this;
         ++(*this);
         return orig;
        }
Lab
  1. Implementing comparison / relational operators
    • For the Time class, define the following comparison / relational operators:
      • time1 == time2
        bool Time::operator == (const Time & rhs) const
        {
         return this->seconds == rhs.seconds;
        }
      • time1 != time2
        bool Time::operator != (const Time & rhs) const
        {
         return !(*this == rhs);
        }
      • time1 > time2
        bool Time::operator > (const Time & rhs) const
        {
         return this->seconds > rhs.seconds;
        }
      • time1 < time2
        bool Time::operator < (const Time & rhs) const {  return this->seconds < rhs.seconds; }
      • time1 >= time2
        bool Time::operator >= (const Time & rhs) const
        {
         return this->seconds >= rhs.seconds;
        }
      • time1 <= time2
        bool Time::operator <= (const Time & rhs) const {  return this->seconds <= rhs.seconds; }
      • View code file.
    • In main(), write some simple code to test your operators
      Time time1(19, 36, 11);
      Time time2(17, 44, 29);
      cout << "time1: " << time1.ToString() << endl; cout << "time2: " << time2.ToString() << endl << endl; // Test the relational operators in Question 2. cout << "Relational operators..." << endl; cout << "time1 == time2: " << (time1 == time2) << endl; cout << "time1 != time2: " << (time1 != time2) << endl; cout << "time1 > time2: " << (time1 > time2) << endl; cout << "time1 >= time2: " << (time1 >= time2) << endl; cout << "time1 < time2: " << (time1 < time2) << endl; cout << "time1 <= time2: " << (time1 <= time2) << endl << endl;
    • View code file.

Lab 3: Binary operators

Lab 3: Binary operators
  1. Overview of Binary Operators
    • Binary operators take two operands
      • i.e. the object itself, plus another operand
    • There are two ways to implement binary operators
      • As a member function
      • As a non-member function
    • We'll see an example of both approaches in the following slides
  2. Defining Member Functions
    • To define binary operators as member functions:
      class Money
      {
      public:
       Money& operator+=(int d);
       Money& operator-=(int d);
       ...
    • To implement binary operators as member functions:
      Money& Money::operator+=(int d)
      {
       dollars += d;
       return *this;
      }
      Money& Money::operator-=(int d)
      {
       dollars -= d;
       return *this;
      }
    • How would you define/implement == and != operators?
  3. Overview of Non-Member Functions
    • You can define binary operators as non-member functions
      • i.e. not part of the class
    • Benefits:
      • No implicit this parameter
      • You must define both parameters explicitly
      • You can define the first parameter to be a non-object
    • This is the preferred way to implement symmetrical binary operators
      • For example:
        money2 = money1 + 10;
        money2 = 10 + money1;
  4. Defining Non-Member Functions
    • To define binary operators as non-member functions:
      class Money
      {
       ...
      };
      Money operator+(const Money & m, int d);
      Money operator+(int d, const Money & m);
    • To implement binary operators as non-member functions:
      Money operator+(const Money & m, int d)
      {
       return Money(m.GetDollars() + d, m.GetCents());
      }
      Money operator+(int d, const Money & m)
      {
       return m + d;
      }
  5. A Special Word about << and >>
    • The << and >> operators have idiomatic meaning in C++
      • Output to a stream, and input from a stream
      • You can implement these as non-member functions
        // Header
        class Money
        {
         ...
        };
        ostream& operator<<(ostream & os, const Money & m); istream& operator>>(istream & is, Money & m);
        // Cpp File
        ostream& operator<<(ostream & os, const Money & m) {  os << "$" << m.GetDollars() << "." << m.GetCents();  return os; } istream& operator>>(istream & is, Money & m)
        {
         int d, c;
         is >> d >> c;
         m.SetDollars(d);
         m.SetCents(c);
         return is;
        }
Lab
  1. Implementing mathematical operators
      • time1 + timespan1 // adds seconds, returns a time
        Time Time::operator + (const Timespan & amount) const
        {
         Time result = *this;
         result.seconds += amount;
         return result;
        }
      • time1 - timespan1 // subtracts seconds, returns a time
        Time Time::operator - (const Timespan & amount) const
        {
         Time result = *this;
         result.seconds -= amount;
         return result;
        }
      • time1 - time2 // returns difference between two times, in seconds
        Timespan Time::operator - (const Time & rhs) const
        {
         return this->seconds - rhs.seconds;
        }
      • time1 += timespan1 // adds and stores a specified number of seconds
        Time& Time::operator += (const Timespan & amount)
        {
         this->seconds += amount;
         return *this;
        }
      • time1 -= timespan1 // subtracts and stores a specified number of seconds
        Time& Time::operator -= (const Timespan & amount)
        {
         this->seconds -= amount;
         return *this;
        }
      • ++time1 // Pre-increments a time by 1 second
        Time Time::operator ++ (int)
        {
         Time orig = *this;
         ++(*this);
         return orig;
        }
      • time1++ // Post-increments a time by 1 second
        Time& Time::operator ++ ()
        {
         this->seconds++;
         return *this;
        }
      • --time1 // Pre-decrements a time by 1 second
        Time Time::operator -- (int)
        {
         Time orig = *this;
         --(*this);
         return orig;
        }
      • time1-- // Post-decrements a time by 1 second
        Time& Time::operator -- ()
        {
         this->seconds--;
         return *this;
        }
      • View code file.
    • In main(), write some simple code to test your operators
      // Test the mathematical operators in Question 3.
      cout << "Mathematical operators..." << endl; cout << "time1 + 15: " << (time1 + 15).ToString() << endl; cout << "time1 - 15: " << (time1 - 15).ToString() << endl; cout << "time1 - time2: " << (time1 - time2) << endl; time1 += 30; cout << "Result of (time1 += 30): " << time1.ToString() << endl; time1 -= 20; cout << "Result of (time1 -= 20): " << time1.ToString() << endl; cout << "++time1: " << (++time1).ToString() << endl; cout << "time1++: " << (time1++).ToString() << endl; cout << "time1 now: " << time1.ToString() << endl; cout << "--time1: " << (--time1).ToString() << endl; cout << "time1--: " << (time1--).ToString() << endl; cout << "time1 now: " << time1.ToString() << endl << endl;
    • View code file.

 

Well done. You have completed the tutorial in the C++ course. The next tutorial is

13. Copying and Assignment


Back to beginning
Copyright © 2016 TalkIT®






If you liked this post, please comment with your suggestions to help others.
If you would like to see more content like this in the future, please fill-in our quick survey.
Scroll to Top