Loading lessons...
Operator Overloading with Friends, Stream & Special Operators, and the Rules
Operator Overloading with Friends, Stream & Special Operators, and the Rules
Member operator functions have one limitation: the left operand must be an object of the class. That is why 2 * v or cout << c cannot be written as members of our class. This lesson uses friend operator functions to solve that, overloads the stream operators << and >>, the subscript [] and function call () operators, and ends with the rules of operator overloading, a guaranteed short question.
1. Overloading Binary Operators Using Friends
A friend operator function takes both operands as arguments, so neither has to be the calling object. The complex-number + as a friend:
class Complex {
float real, imag;
public:
friend Complex operator+(Complex a, Complex b); // two arguments
};
Complex operator+(Complex a, Complex b) {
return Complex(a.real + b.real, a.imag + b.imag);
}C3 = C1 + C2; is now interpreted as C3 = operator+(C1, C2);.
When a friend is necessary
Consider scaling a vector: v2 = v1 * 2; works with a member function, since it means v1.operator*(2). But v2 = 2 * v1; means 2.operator*(v1), and the built-in int has no such member. A friend with the arguments (int, Vector) solves this.
#include <iostream>
using namespace std;
const int SIZE = 3;
class Vector {
int v[SIZE];
public:
Vector() {
for (int i = 0; i < SIZE; i++) {
v[i] = 0;
}
}
Vector(const int* x) {
for (int i = 0; i < SIZE; i++) {
v[i] = x[i];
}
}
friend Vector operator*(int k, const Vector& b); // 2 * v
friend Vector operator*(const Vector& b, int k); // v * 2
void show() const {
cout << "(";
for (int i = 0; i < SIZE; i++) {
cout << v[i] << (i < SIZE - 1 ? ", " : "");
}
cout << ")" << endl;
}
};
Vector operator*(int k, const Vector& b) {
Vector c;
for (int i = 0; i < SIZE; i++) {
c.v[i] = k * b.v[i];
}
return c;
}
Vector operator*(const Vector& b, int k) {
return k * b; // reuse the first function
}
int main() {
int x[SIZE] = {2, 4, 6};
Vector m(x);
Vector p = 2 * m; // operator*(2, m): only possible with a friend
Vector q = m * 3; // operator*(m, 3)
cout << "m = ";
m.show();
cout << "2 * m = ";
p.show();
cout << "m * 3 = ";
q.show();
return 0;
}Output:
m = (2, 4, 6)
2 * m = (4, 8, 12)
m * 3 = (6, 12, 18)Unary operator as a friend
A unary operator as a friend takes one argument. To change the operand, pass it by reference:
friend void operator-(Space& s); // -S calls operator-(S)
void operator-(Space& s) {
s.x = -s.x;
s.y = -s.y;
s.z = -s.z;
}Member vs friend operator functions
| Member operator function | Friend operator function |
|---|---|
| left operand must be an object of the class | either operand can be of another type (2 * v) |
| unary: 0 arguments, binary: 1 | unary: 1 argument, binary: 2 |
has this | no this |
required for =, (), [], -> | cannot be used for =, (), [], -> |
natural for operators that change the object (+=, ++) | natural for symmetric operators (+, ==) and stream operators |
2. Overloading the Stream Operators << and >>
cout << c means operator<<(cout, c). The left operand is cout, an object of class ostream, which we cannot modify, so << must be overloaded as a friend (or a non-member) function. It must return the stream by reference so that output can be chained: cout << a << b.
friend ostream& operator<<(ostream& out, const Complex& c);
friend istream& operator>>(istream& in, Complex& c);A complete program that reads and prints Complex numbers using these two operators:
#include <iostream>
using namespace std;
class Complex {
float real, imag;
public:
Complex(float r = 0, float i = 0) {
real = r;
imag = i;
}
friend ostream& operator<<(ostream& out, const Complex& c);
friend istream& operator>>(istream& in, Complex& c);
friend Complex operator+(const Complex& a, const Complex& b);
};
ostream& operator<<(ostream& out, const Complex& c) {
out << c.real;
if (c.imag >= 0) {
out << " + j" << c.imag;
} else {
out << " - j" << -c.imag;
}
return out; // return the stream for chaining
}
istream& operator>>(istream& in, Complex& c) {
in >> c.real >> c.imag;
return in;
}
Complex operator+(const Complex& a, const Complex& b) {
return Complex(a.real + b.real, a.imag + b.imag);
}
int main() {
Complex a, b;
cout << "Enter two complex numbers (real imag): ";
cin >> a >> b; // operator>>(operator>>(cin, a), b)
cout << endl;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << a + b << endl;
return 0;
}Input:
3 4
1.5 -6Output:
Enter two complex numbers (real imag):
a = 3 + j4
b = 1.5 - j6
a + b = 4.5 - j23. Overloading the Subscript Operator []
Overloading [] lets an object be indexed like an array, with bounds checking. It must be a member function, and it returns a reference so that it can be used on the left of = (as in Lesson 9).
#include <iostream>
#include <cstdlib>
using namespace std;
class SafeArray {
enum {
SIZE = 5
};
int a[SIZE];
public:
SafeArray() {
for (int i = 0; i < SIZE; i++) {
a[i] = 0;
}
}
int& operator[](int i) {
if (i < 0 || i >= SIZE) {
cout << "Index " << i << " out of bounds" << endl;
exit(1);
}
return a[i]; // reference: arr[2] = 7 works
}
};
int main() {
SafeArray arr;
for (int i = 0; i < 5; i++) {
arr[i] = i * 10; // arr.operator[](i) = i * 10
}
cout << "arr[3] = " << arr[3] << endl;
arr[7] = 1; // caught instead of corrupting memory
cout << "not reached" << endl;
return 0;
}Output:
arr[3] = 30
Index 7 out of bounds4. Overloading the Function Call Operator ()
Overloading () makes an object callable like a function. Such objects are called function objects or functors; the STL uses them heavily (Unit IV).
#include <iostream>
using namespace std;
class Line { // y = m * x + c
double m, c;
public:
Line(double slope, double intercept) {
m = slope;
c = intercept;
}
double operator()(double x) const {
return m * x + c;
}
};
int main() {
Line f(2, 1); // f(x) = 2x + 1
for (int x = 0; x <= 3; x++) {
cout << "f(" << x << ") = " << f(x) << endl; // f.operator()(x)
}
return 0;
}Output:
f(0) = 1
f(1) = 3
f(2) = 5
f(3) = 75. Rules for Overloading Operators
- Only existing operators can be overloaded. New operator symbols (such as
**or<>) cannot be created. - The overloaded operator must have at least one operand of a user-defined type (class or enum). The meaning of
int + intcannot be changed. - The basic meaning should be kept:
+should add, not subtract (good practice, not enforced). - Precedence, associativity and the number of operands (arity) cannot be changed.
a + b * calways multiplies first. - Overloaded operators follow the syntax rules of the original operators.
- Default arguments are not allowed in operator functions (except
operator()). - Some operators cannot be overloaded at all (table below).
- Some operators cannot be overloaded using friend functions; they must be members:
=,(),[],->. - Unary operators overloaded as members take no explicit argument; as friends, one. Binary: one as members, two as friends.
- When a member function is used for a binary operator, the left operand must be an object of the class.
- Binary arithmetic operators such as
+,-,*,/must explicitly return a value.
Operators that cannot be overloaded
| Operator | Name | Why not |
|---|---|---|
. | member access (dot) | needed to access members; overloading it would make member access unreliable |
.* | pointer-to-member access | same reason |
:: | scope resolution | works on names at compile time, not on values |
?: | conditional (ternary) | its short-circuit evaluation could not be preserved |
sizeof | size operator | evaluated at compile time; its meaning must be fixed |
typeid | run-time type information | must identify types reliably |
Operators that must be members (cannot be friends)
= (assignment), () (function call), [] (subscript), -> (class member access through a pointer).
Key points to remember
- Friend operator functions take all operands as arguments; needed when the left operand is not a class object (
2 * v,cout << c). <<and>>are overloaded as friends returningostream&/istream&so they can be chained.[]returns a reference soarr[i] = xworks;()makes function objects.- Cannot overload:
..*::?:sizeoftypeid. Must be members:=()[]->. - Overloading cannot change precedence, associativity or the number of operands, or create new operators.
📝 IPU End-Term Exam Corner (5-10 Marks)
- Q1. State the rules for overloading operators. List the operators that cannot be overloaded. (5 Marks)
- Write: at least eight rules, the "cannot overload" table and the "must be members" list.
- Q2. Overload the
<<and>>operators for aComplexclass. Why must they be friend functions? (10 Marks) - Write: the explanation that the left operand is
cout/cin, the program, and why the stream is returned by reference. - Q3. Why is a friend function needed to evaluate
2 * vwherevis an object? Write the program. (5 Marks) - Q4. Differentiate between overloading an operator with a member function and with a friend function. (5 Marks)
- Q5. Overload the subscript operator
[]to give a safe array. (5 Marks)