LearnFrenzy
Sign in Take a free test

C++ Programming · Topic 17 of 27

Operator Overloading

  • 4 exercises
  • 60 questions
  • ~60 min
  • Answers explained

Coding Techniques

Operator Overloading · Study material

The canonical set of arithmetic operators

Write the compound operators (+=, -=, *=) as members, then the binary operators as non-member friends built on them. One place holds the logic, both operand orders work, and comparisons come from a defaulted <=>.

#include <compare>
#include <iostream>

// The canonical set: compound ops as members, binary ops as non-members built on them
class Money {
    long paise_;
public:
    explicit constexpr Money(long p = 0) : paise_(p) {}
    Money& operator+=(Money o) { paise_ += o.paise_; return *this; }
    Money& operator-=(Money o) { paise_ -= o.paise_; return *this; }
    Money& operator*=(long k)  { paise_ *= k; return *this; }
    friend Money operator+(Money a, Money b) { return a += b; }
    friend Money operator-(Money a, Money b) { return a -= b; }
    friend Money operator*(Money a, long k)  { return a *= k; }
    friend Money operator*(long k, Money a)  { return a *= k; }
    auto operator<=>(const Money&) const = default;
    friend std::ostream& operator<<(std::ostream& os, Money m) {
        return os << "Rs " << m.paise_ / 100 << '.' << (m.paise_ % 100 < 10 ? "0" : "") << m.paise_ % 100;
    }
};

int main() {
    Money price(24950), shipping(4000);
    Money total = 2 * price + shipping;
    std::cout << total << ' ' << (total > Money(50000)) << ' ' << total - Money(3900) << '\n';
    return 0;
}

Output

Rs 539.00 1 Rs 500.00

Canonical signatures to copy

T& operator=(const T& other);                 // copy assignment (member)
T& operator=(T&& other) noexcept;             // move assignment (member)
T& operator+=(const T& rhs);                  // compound: member, returns *this
friend T operator+(T lhs, const T& rhs);      // binary: non-member, by value
bool operator==(const T&) const = default;    // C++20
auto operator<=>(const T&) const = default;   // C++20
T& operator++();                              // prefix
T  operator++(int);                           // postfix
Elem& operator[](std::size_t i);              // subscript, non-const
const Elem& operator[](std::size_t i) const;  // subscript, const
R operator()(Args...) const;                  // function call
explicit operator bool() const;               // safe boolean test
friend std::ostream& operator<<(std::ostream&, const T&);
friend std::istream& operator>>(std::istream&, T&);

Overload only when the meaning is obvious

// ✔ Natural meanings
Vec2 a = b + c;            // vector addition
if (d1 < d2) …             // date order
std::cout << invoice;      // printing
matrix(i, j) = 0;          // element access

// ✘ Surprising meanings – use named functions instead
playlist + song;           // add? concatenate? returns what?  → playlist.add(song)
employee++;                // promote? age? → employee.promote()
!account;                  // closed? empty? → account.is_closed()

Operator overloading checklist

  • Keep the usual meaning and the usual return types.
  • Return *this by reference from =, compound operators and prefix ++/--.
  • Make symmetric binary operators non-members (friends if needed).
  • Provide const and non-const versions of [] and *.
  • Prefer defaulted <=> and == in C++20.
  • Make conversion operators explicit.
  • Keep related operators consistent (a + b == (a += b)).

Ready to test your Programming?

Timed online tests with instant scores and explanations.

About this section

About C++ Programming

C++ adds object-oriented programming, templates and the powerful Standard Template Library (STL) to C. It powers game engines, browsers, trading systems and most competitive programming. This section takes you from basic syntax to classes, inheritance, polymorphism, modern C++ (C++11 to C++23) and the STL – every concept with runnable examples and practice questions checked on a real compiler.

Why it matters

  • OOP concepts – classes, inheritance, polymorphism, encapsulation – are asked in almost every interview
  • C++ with the STL is the most popular language for competitive programming and DSA rounds
  • Questions on constructors, virtual functions, references and smart pointers decide technical rounds
  • Modern C++ skills are in demand at product companies, fintech and game studios

Who it is for

  • School students (Class 11–12 computer science with C++) preparing for board exams and practicals
  • College students (B.Tech, BCA, MCA) learning OOP and data structures for semester exams and labs
  • Freshers preparing for placements, coding tests and C++ technical interviews
  • Competitive programmers who want to master the STL

What every topic gives you

  • Study material in five tabs: concepts with runnable examples, coding techniques, programs, interview questions and a cheat sheet
  • MCQs that check your understanding of every concept
  • "Predict the output" puzzles – the trickiest part of written tests
  • "Find the error" programs that train you to spot bugs quickly
  • Complete programs with solutions and real output, verified on a compiler

Asked in

  • Campus placements
  • Product company interviews
  • Coding rounds & DSA
  • Competitive programming
  • GATE CS
  • University exams

How to use this section

  1. Read the study material of a topic and run the examples yourself.
  2. Practise the four exercises – MCQs, output, errors, programs – and read every explanation.
  3. Test yourself with the timed online test, then revise the topics you got wrong.

Search LearnFrenzy

Esc

Quick links