Intermediate level · Module 1: Classes, Constructors and Object Lifetime · Lesson 2 of 3
const Correctness and Operator Overloading
Mark what does not change as const, and give classes natural operators such as ==, < and <<.
In this lesson you will
- Apply const to member functions, parameters and references
- Overload ==, <, + and << for a value class
Key concepts
const member functionoperator overloadingoperator<< for streamsdefaulted comparisons (C++20)
The lesson
const correctness means marking everything that should not change: const member functions, const reference parameters and const variables. The compiler then catches accidental changes, and const objects can still be used with your class.
Operators can be overloaded for your types: Money operator+(const Money& a, const Money& b). Overload only where the meaning is obvious. In C++20, bool operator==(const Money&) const = default; generates equality from all members.
Overloading std::ostream& operator<<(std::ostream& out, const Money& m) lets you print objects with std::cout << m. Return the stream so outputs can be chained.
Step by step
- Make Money's getters const.
- Add a defaulted operator==.
- Add operator+ that rejects different currencies.
- Add operator<< that prints '1,250.00 SSP' style output.
Practice activity
Complete the Money practical activity and test it with a provided program.
Expected result: The test program compiles and passes, including the rejection of adding SSP to USD.
Check your understanding
-
Why should operator<< return the stream?
Show answer
So output operations can be chained, as in std::cout << a << b.
-
What does = default do for operator== in C++20?
Show answer
Generates a member-by-member equality comparison.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.