Lesson 5 of 5
Practice & Quiz - References, Const & Operators
Consolidate your understanding of references vs pointers, const-correctness, operator overloading, and the copy-and-swap idiom with a practical exercise and 5 quiz questions.
Practical Exercise - Complex Number with Operator Overloading
#include <iostream>
#include <cmath>
#include <sstream>
class Complex {
public:
double re, im;
Complex(double re = 0, double im = 0) : re(re), im(im) {}
// Compound assignment - member
Complex& operator+=(const Complex& o) { re+=o.re; im+=o.im; return *this; }
Complex& operator-=(const Complex& o) { re-=o.re; im-=o.im; return *this; }
Complex& operator*=(const Complex& o) {
double r = re*o.re - im*o.im;
double i = re*o.im + im*o.re;
re = r; im = i; return *this;
}
// Unary
Complex operator-() const { return {-re, -im}; }
Complex conjugate() const { return {re, -im}; }
double magnitude() const { return std::sqrt(re*re + im*im); }
// Comparison
friend bool operator==(const Complex& a, const Complex& b) {
return std::abs(a.re-b.re) < 1e-9 && std::abs(a.im-b.im) < 1e-9;
}
// Stream output
friend std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.re;
if (c.im >= 0) os << "+";
return os << c.im << "i";
}
};
// Binary non-member - symmetric
inline Complex operator+(Complex a, const Complex& b) { return a+=b; }
inline Complex operator-(Complex a, const Complex& b) { return a-=b; }
inline Complex operator*(Complex a, const Complex& b) { return a*=b; }
int main() {
Complex a{3, 4}, b{1, -2};
std::cout << "a = " << a << "\n";
std::cout << "b = " << b << "\n";
std::cout << "a+b = " << (a+b) << "\n"; // 4+2i
std::cout << "a*b = " << (a*b) << "\n"; // 3*1-4*(-2) + (3*(-2)+4*1)i = 11-2i
std::cout << "|a| = " << a.magnitude() << "\n"; // 5.0
std::cout << "conj(a) = " << a.conjugate() << "\n"; // 3-4i
return 0;
}Module Quiz
What happens when you write `int& r = x; r = y;` where both x and y are ints?
Tip
Tip
Practice Practice Quiz References Const Operators in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Aliases vs Pointers, Shallow vs Deep Copy, Copy-and-Swap Idiom & Complete Operator Suites
Practice Task
Note
Practice Task - (1) Write a working example of Practice Quiz References Const Operators from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Practice Quiz References Const Operators is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready cpp code.
Finished this lesson?