Operator Overloading
Open in the Padhaiko app4.1 Overloadable and non-overloadable operators
Operator overloading lets C++ operators (+, -, ++, ==, <<, etc.) work on user-defined class types in a natural, readable way (c3 = c1 + c2; instead of c3 = c1.add(c2);). It is a form of compile-time polymorphism.
| Category | Operators |
|---|---|
| Overloadable Operators | Arithmetic (+, -, *, /, %), Increment/Decrement (++, --), Relational (==, !=, <, >, <=, >=), Logical (&&, logical OR, !), Bitwise (&, bitwise OR, ^, ~, <<, >>), Assignment (=, +=, -=, etc.), Subscript [], Call (), Member access ->, ->*, Memory (new, delete, new[], delete[]), Comma , |
| Non-Overloadable Operators | Scope resolution ::, Member selection ., Pointer-to-member selection .*, Ternary conditional ?:, Size query sizeof (also typeid, alignof) |
Fundamental Rules of Operator Overloading
- No New Operator Symbols: Only existing C++ operators can be overloaded (you cannot invent
**for exponentiation). - Arity, Precedence, and Associativity Are Fixed: Unary operators remain unary, binary remain binary, and
+always keeps lower precedence than*. - At Least One User-Defined Operand: You cannot redefine how
+works on two built-inints. - Member-Only Operators: Assignment
=, function call(), subscript[], and member access->must be overloaded as non-static member functions, never asfriendfunctions.
4.2 Syntax of operator overloading
An overloaded operator is a special function whose name starts with the operator keyword followed by the operator symbol:
// Inside a class (member function):
ReturnType operator@(ParameterList);
// Outside a class (non-member / friend function):
ReturnType operator@(ClassName lhs, ...);- Member form:
c1 + c2is translated by the compiler intoc1.operator+(c2). - Non-member form:
c1 + c2is translated intooperator+(c1, c2).
4.3 Operator overloading using member operator functions
When an operator is overloaded as a member function, the left-hand operand (for binary) or the single operand (for unary) is passed implicitly via the this pointer:
- Unary member operator: Takes 0 explicit arguments (
Complex operator-() const;). - Binary member operator: Takes 1 explicit argument (
Complex operator+(const Complex &rhs) const;).
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
Complex operator+(const Complex &rhs) const {
return Complex(re + rhs.re, im + rhs.im);
}
};Limitation of member operators: c1 + 5.0 can work if a converting constructor Complex(double) exists, because c1.operator+(Complex(5.0)) converts the right operand; however, 5.0 + c1 fails for a member operator because 5.0 is a primitive double and cannot invoke 5.0.operator+(c1).
4.4 Operator overloading using non member functions
To support expressions where the left-hand operand is a built-in type (such as 5.0 + c1 or cout << c1), overload the operator as a non-member function (usually declared friend inside the class so it can read private members):
- Unary non-member (
friend) operator: Takes 1 argument (friend Complex operator-(const Complex &c);). - Binary non-member (
friend) operator: Takes 2 arguments (friend Complex operator+(double k, const Complex &c);).
| Aspect | Member Operator Function | Non-Member (friend) Operator Function |
|---|---|---|
| Unary Arguments | 0 explicit arguments (this is operand) | 1 explicit argument |
| Binary Arguments | 1 explicit argument (this is left operand) | 2 explicit arguments (lhs, rhs) |
| Left Operand Conversion | Implicit conversions do not apply to this | Implicit conversions apply to both operands |
| Mandatory Cases | =, (), [], -> | <<, >> with ostream/istream, scalar + obj |
4.5 Unary operator overloading
Unary operators operate on a single object (e.g., -obj, ++obj, obj++, !obj).
Prefix vs. Postfix ++ and --
Because both prefix (++c) and postfix (c++) use the same ++ symbol, C++ uses a dummy int parameter to distinguish postfix:
- Prefix (
Counter &operator++()): Increments the object first and returns*thisby reference. - Postfix (
Counter operator++(int)): Saves the old state in a temporary copy, increments*this, and returns the old copy by value (dummyintis never named or used).
#include <iostream>
using namespace std;
class Counter {
int val;
public:
Counter(int v = 0) : val(v) {}
Counter &operator++() { // Prefix: ++c
++val;
return *this;
}
Counter operator++(int) { // Postfix: c++
Counter old = *this;
++val;
return old;
}
int get() const { return val; }
};
int main() {
Counter c(5);
cout << (++c).get() << " "; // Increments to 6, prints 6
cout << (c++).get() << " "; // Returns copy (6), then increments to 7
cout << c.get() << endl; // Prints 7
return 0;
}4.6 Binary operator overloading
Binary operators take two operands: arithmetic (+, -, *), relational (==, <), or compound assignment (+=).
- Arithmetic (
+): Should beconstand return a new object by value without modifying either operand. - Relational (
==,<): Should beconstand returnbool. - Compound Assignment (
+=) / Copy Assignment (=): Modifies*thisand returns*thisby reference (T &) to support chaining (a += b;ora = b = c;).
4.7 Type conversion between objects
While C++ converts built-in types automatically (int to double), conversions involving class types require programmer-defined rules across three scenarios:
| Conversion Direction | Mechanism | Where Defined |
|---|---|---|
| Basic Type -> Class Type | Single-argument converting constructor ClassName(BasicType x) | Inside the destination class |
| Class Type -> Basic Type | Conversion operator function operator BasicType() const | Inside the source class (no return type written, no args) |
| Class A -> Class B | Either converting constructor B(const A &) in B, OR conversion operator operator B() const in A | Choose one (defining both causes ambiguity) |
4.8 Explicit constructors
A single-argument constructor (or a constructor where all subsequent arguments have defaults) acts implicitly as a converting constructor. Sometimes implicit conversion causes silent bugs—for example, passing an integer 10 where a Vector of size 10 is expected, or comparing vec == 10.
Prefixing a constructor with explicit disables implicit conversions and copy-initialization (T obj = val;), permitting only direct initialization (T obj(val); or static_cast<T>(val)):
class Buffer {
int size;
public:
explicit Buffer(int s) : size(s) {}
int getSize() const { return size; }
};
void printSize(Buffer b) { /* ... */ }
int main() {
Buffer b1(64); // OK: direct initialization
// Buffer b2 = 64; // Compile error: copy-initialization blocked by explicit
// printSize(64); // Compile error: implicit int -> Buffer blocked
printSize(Buffer(64)); // OK: explicit conversion
return 0;
}Worked Examples
1
Write a C++ class Distance storing feet (int) and inches (double, normalized so 0 <= inches < 12). Overload:
- Binary
+(member) to add twoDistanceobjects, - Prefix
++to add1inch (normalizing overflow), operator double() constto convertDistanceto total feet (double), and- Relational
<as afriendfunction.
Trace the result for d1(5, 8.0) and d2(3, 7.0).
Normalization Helper and Operator Definitions: Whenever inches reach or exceed 12.0, carry int(inches / 12) into feet and keep the remainder in inches:
#include <iostream>
using namespace std;
class Distance {
int feet;
double inches;
void normalize() {
while (inches >= 12.0) {
inches -= 12.0;
++feet;
}
}
public:
Distance(int f = 0, double in = 0.0) : feet(f), inches(in) { normalize(); }
Distance operator+(const Distance &rhs) const {
return Distance(feet + rhs.feet, inches + rhs.inches);
}
Distance &operator++() {
inches += 1.0;
normalize();
return *this;
}
operator double() const {
return feet + inches / 12.0;
}
friend bool operator<(const Distance &a, const Distance &b) {
return (a.feet * 12.0 + a.inches) < (b.feet * 12.0 + b.inches);
}
void show() const { cout << feet << "ft " << inches << "in"; }
};
int main() {
Distance d1(5, 8.0), d2(3, 7.0);
Distance d3 = d1 + d2;
++d3;
double totalFeet = d3; // Uses operator double() const
cout << "d3 = "; d3.show();
cout << ", in feet = " << totalFeet << ", d2 < d1? " << (d2 < d1) << endl;
return 0;
}Tracing for d1(5, 8.0) and d2(3, 7.0):
d1 + d2:feet = 5 + 3 = 8,inches = 8.0 + 7.0 = 15.0-> normalized to9 ft 3 in.++d3: adds1.0inch ->9 ft 4 in.double totalFeet = d3: invokesoperator double() const->9 + 4.0 / 12.0 = 9.33333(printed as9.33333).d2 < d1:3*12 + 7 = 43 < 5*12 + 8 = 68->1(true).
Output: d3 = 9ft 4in, in feet = 9.33333, d2 < d1? 1
2
Demonstrate class-to-class type conversion between Polar (radius, angleRad) and Cartesian (x, y) using a converting constructor in Cartesian, and compute (x, y) for Polar(10.0, 0.0) and Polar(5.0, 3.14159265 / 2.0).
Choosing One Conversion Mechanism (Destination Converting Constructor): Cartesian(const Polar &p) reads p.getR() and p.getTheta() via public getters (or friend access) and sets x = r * cos(theta), y = r * sin(theta). We do not also define Polar::operator Cartesian(), avoiding ambiguity.
#include <iostream>
#include <cmath>
using namespace std;
class Polar {
double r, theta;
public:
Polar(double rad, double ang) : r(rad), theta(ang) {}
double getR() const { return r; }
double getTheta() const { return theta; }
};
class Cartesian {
double x, y;
public:
Cartesian(double xx = 0, double yy = 0) : x(xx), y(yy) {}
Cartesian(const Polar &p) { // Polar -> Cartesian
x = p.getR() * cos(p.getTheta());
y = p.getR() * sin(p.getTheta());
}
void show() const { cout << "(" << x << ", " << y << ")" << endl; }
};
int main() {
Polar p1(10.0, 0.0);
Polar p2(5.0, 3.141592653589793 / 2.0);
Cartesian c1 = p1;
Cartesian c2 = p2;
c1.show();
c2.show();
return 0;
}Tracing Coordinates:
- For
p1(10.0, 0.0):x = 10 * cos(0) = 10,y = 10 * sin(0) = 0. - For
p2(5.0, pi/2):x = 5 * cos(pi/2) ~ 0(IEEE floating point ~3.06e-16),y = 5 * sin(pi/2) = 5.
c1 converts to (10, 0) and c2 converts to (0, 5) (with floating-point x near 3.06e-16 for pi/2).
Exercises
Exercises — Operator Overloading
List the operators that cannot be overloaded in C++, and explain why operators like << (stream insertion) and expressions like 5 + obj must be overloaded as non-member (friend) functions.
Non-Overloadable Operators: The five classic non-overloadable operators in C++ are:
::(scope resolution).(direct member access).*(pointer-to-member access)?:(ternary conditional)sizeof(along withtypeidandalignof)
Why << and 5 + obj Require Non-Member Overloading: In a member operator lhs.operator op(rhs), the left operand lhs must be an object of the class you are writing (and no implicit conversion happens on lhs).
- For
cout << obj, the left operand isstd::ostream(cout), whose class definition we cannot modify. Thusoperator<<(ostream &, const MyClass &)must be a non-member (friend) function. - For
5 + obj, the left operand isint(5), which has nooperator+(MyClass)method. A non-memberfriend MyClass operator+(int, const MyClass &)acceptsintas its first parameter cleanly.
Non-overloadable operators are ::, ., .*, ?:, and sizeof (typeid, alignof). << and 5 + obj require non-member (friend) overloads because their left-hand operands (ostream and int) are not objects of our user-defined class.
How does C++ distinguish between prefix (++x) and postfix (x++) unary operator overloading? Write both functions for a Time class (seconds) and state what (++t) vs (t++) evaluates to when t starts at 10.
Prefix vs. Postfix Signature Convention:
- Prefix (
T &operator++()): Takes no parameter, increments the object first, and returns*thisby reference (yielding the new value). - Postfix (
T operator++(int)): Takes an unused dummyintparameter, saves a temporary copy of the original state, increments*this, and returns the saved copy by value (yielding the old value).
Trace for t = 10:
++tincrementstfrom10to11and evaluates to11.t++returns a copy holding11while incrementingtto12.
Prefix uses T &operator++() (returns incremented *this, evaluating to 11), while postfix uses a dummy int parameter T operator++(int) (returns old copy 11 and leaves t at 12).
Explain the three types of type conversions involving classes in C++, and state how ambiguity can occur in class-to-class conversion.
Three Conversion Categories:
- Basic Type -> Class Type: Implemented via a single-argument constructor
ClassName(BasicType val)in the target class. - Class Type -> Basic Type: Implemented via a member conversion operator
operator BasicType() constin the source class (no return type, no parameters). - Class A -> Class B: Implemented either as a converting constructor
B(const A &)in destination classB, or as a conversion operatoroperator B() constin source classA.
Class-to-Class Ambiguity: If both A::operator B() const and B::B(const A &) are defined simultaneously, writing B b = a; gives the compiler two equally valid conversion paths (a.operator B() vs B(a)), causing an ambiguous conversion compile error. Define only one of the two.
Basic-to-class uses a single-argument constructor; class-to-basic uses operator BasicType() const; class-to-class uses either a destination constructor or a source conversion operator. Defining both in class-to-class conversion creates an ambiguous-conversion compile error.
What is the purpose of an explicit constructor? Show a code snippet where omitting explicit causes an unexpected implicit conversion and adding explicit catches it at compile time.
Purpose of explicit: Without explicit, any constructor callable with one argument acts as an implicit converter, allowing ClassType obj = arg; or passing arg silently to a function expecting ClassType. Marking the constructor explicit forces callers to construct objects intentionally (ClassType obj(arg); or ClassType(arg)).
Code Demonstration:
class Meter {
double m;
public:
explicit Meter(double val) : m(val) {}
double value() const { return m; }
};
void show(Meter x) { /* ... */ }
int main() {
Meter m1(5.0); // Valid: direct initialization
// Meter m2 = 5.0; // Error when explicit: implicit double -> Meter disabled
// show(5.0); // Error when explicit: must write show(Meter(5.0))
return 0;
}explicit prevents single-argument constructors from performing silent implicit conversions (Meter m2 = 5.0; or show(5.0)), requiring direct initialization (Meter m1(5.0);).
Overload operator+ and operator* for a Complex class (real, imag), and compute (2 + 3i) * (4 - i) + (1 + 2i). Show both the algebraic steps and the C++ output.
Complex Multiplication and Addition Rules: For a + bi and c + di:
(a + bi) * (c + di) = (ac - bd) + (ad + bc)i(a + bi) + (c + di) = (a + c) + (b + d)i
#include <iostream>
using namespace std;
class Complex {
double re, im;
public:
Complex(double r = 0, double i = 0) : re(r), im(i) {}
Complex operator+(const Complex &rhs) const {
return Complex(re + rhs.re, im + rhs.im);
}
Complex operator*(const Complex &rhs) const {
return Complex(re * rhs.re - im * rhs.im,
re * rhs.im + im * rhs.re);
}
void show() const { cout << re << " + " << im << "i" << endl; }
};
int main() {
Complex a(2, 3), b(4, -1), c(1, 2);
Complex res = a * b + c;
res.show();
return 0;
}Evaluating (2 + 3i) * (4 - i) + (1 + 2i):
- First,
*has higher precedence than+:real = 2*4 - 3*(-1) = 8 + 3 = 11,imag = 2*(-1) + 3*4 = -2 + 12 = 10->11 + 10i. - Next, add
(1 + 2i):real = 11 + 1 = 12,imag = 10 + 2 = 12->12 + 12i.
(2 + 3i) * (4 - i) + (1 + 2i) = 12 + 12i. The C++ program outputs 12 + 12i.