Operator Overloading
Basic Concepts
- Overloaded operators are functions with special names: composed of the keyword
operatorfollowed by the symbol of the operator being defined. - When an overloaded operator is a member function,
thisis bound to the left-hand operand. The number of parameters for a member operator function is one less than the number of operands. - Only most existing operators can be overloaded; new operator symbols cannot be invented.
- The precedence and associativity of overloaded operators remain the same as their built-in counterparts.
- Calling methods:
data1 + data2;operator+(data1, data2);
- Whether it is a member function:
- Assignment (
=), subscript ([]), function call (()), and member access arrow (->) operators must be members. - Compound assignment operators are generally members.
- Operators that change the state of an object or are closely related to a given type are usually members, such as increment, dereference.
- Operators with symmetry, such as arithmetic, equality, relational, and bitwise operators, are usually non-member functions.
- Assignment (
Operators:
| Can be overloaded | Cannot be overloaded | ||
|---|---|---|---|
+, -, *, /, %, ^ | ::, .*, ., ? :, | ||
&, ` | ` | ~, !, ,, = | |
<, >, <=, >=, ++, -- | |||
<<, >>, ==, !=, &&, ` | ` | ||
+=, -=, /=, %=, ^=, &= | |||
| ` | =, *=, <<=, >>=, [], ()` | ||
->, ->*, new, new[], delete, delete[] |
Basics of Operator Overloading
Operator overloading is achieved by defining special member functions or friend functions. These functions are named by combining the operator symbol with the keyword operator.
Syntax
class ClassName {
public:
// As a member function overload
ReturnType operator Symbol(Parameters) {
// Implementation
}
// As a friend function overload
friend ReturnType operator Symbol(ClassName&, Parameters);
};
Rules for Overloading Operators
- Member function vs. friend function: Member functions can access private members of the class, but the first operand must be an object of that class. Friend functions are not part of the class but can access private members, and both operands can be of arbitrary types.
- Return type: Overloading the assignment operator usually returns
*thisto support chained assignments. - Parameters: The number of parameters for an overloaded operator depends on the native behavior of the operator.
- Prefix vs. postfix: For increment and decrement operators, both prefix and postfix versions can be overloaded.
Common Operator Overloads
Addition Operator +
class Complex {
public:
Complex(double real, double imag) : real_(real), imag_(imag) {}
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
private:
double real_;
double imag_;
};
Subtraction Operator –
Complex operator-(const Complex& other) const {
return Complex(real_ - other.real_, imag_ - other.imag_);
}
Multiplication Operator *
Complex operator*(const Complex& other) const {
return Complex(real_ * other.real_ - imag_ * other.imag_,
real_ * other.imag_ + imag_ * other.real_);
}
Division Operator /
Complex operator/(const Complex& other) const {
double denom = other.real_ * other.real_ + other.imag_ * other.imag_;
return Complex((real_ * other.real_ + imag_ * other.imag_) / denom,
(imag_ * other.real_ - real_ * other.imag_) / denom);
}
Assignment Operator =
Complex& operator=(const Complex& other) {
if (this != &other) {
real_ = other.real_;
imag_ = other.imag_;
}
return *this;
}
Increment/Decrement Operators ++/–
Complex& operator++() { // Prefix ++
++real_;
return *this;
}
Complex operator++(int) { // Postfix ++
Complex old(*this);
++real_;
return old;
}
Complex& operator--() { // Prefix --
--real_;
return *this;
}
Complex operator--(int) { // Postfix --
Complex old(*this);
--real_;
return old;
}
Stream Insertion/Extraction Operators << and >>
std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real_ << (c.imag_ >= 0 ? "+" : "") << c.imag_ << "i";
return os;
}
std::istream& operator>>(std::istream& is, Complex& c) {
double real, imag;
char ch1, ch2, ch3;
is >> real >> ch1 >> imag >> ch2 >> ch3;
if (ch1 == '+' && ch2 == 'i' && ch3 == '\n') {
c = Complex(real, imag);
} else {
is.setstate(std::ios::failbit);
}
return is;
}
Example Code
Below is a complete example demonstrating how to overload addition, subtraction, multiplication, division, assignment, increment/decrement operators, and stream insertion/extraction operators.
#include <iostream>
#include <complex>
class Complex {
public:
Complex(double real, double imag) : real_(real), imag_(imag) {}
// Addition
Complex operator+(const Complex& other) const {
return Complex(real_ + other.real_, imag_ + other.imag_);
}
// Subtraction
Complex operator-(const Complex& other) const {
return Complex(real_ - other.real_, imag_ - other.imag_);
}
// Multiplication
Complex operator*(const Complex& other) const {
return Complex(real_ * other.real_ - imag_ * other.imag_,
real_ * other.imag_ + imag_ * other.real_);
}
// Division
Complex operator/(const Complex& other) const {
double denom = other.real_ * other.real_ + other.imag_ * other.imag_;
return Complex((real_ * other.real_ + imag_ * other.imag_) / denom,
(imag_ * other.real_ - real_ * other.imag_) / denom);
}
// Assignment
Complex& operator=(const Complex& other) {
if (this != &other) {
real_ = other.real_;
imag_ = other.imag_;
}
return *this;
}
// Increment
Complex& operator++() { // Prefix ++
++real_;
return *this;
}
Complex operator++(int) { // Postfix ++
Complex old(*this);
++real_;
return old;
}
// Decrement
Complex& operator--() { // Prefix --
--real_;
return *this;
}
Complex operator--(int) { // Postfix --
Complex old(*this);
--real_;
return old;
}
// Output
friend std::ostream& operator<<(std::ostream& os, const Complex& c);
private:
double real_;
double imag_;
};
// Output
std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << c.real_ << (c.imag_ >= 0 ? "+" : "") << c.imag_ << "i";
return os;
}
int main() {
Complex c1(3.0, 4.0);
Complex c2(1.0, 2.0);
std::cout << "c1: " << c1 << std::endl;
std::cout << "c2: " << c2 << std::endl;
Complex sum = c1 + c2;
std::cout << "Sum: " << sum << std::endl;
Complex diff = c1 - c2;
std::cout << "Difference: " << diff << std::endl;
Complex prod = c1 * c2;
std::cout << "Product: " << prod << std::endl;
Complex quot = c1 / c2;
std::cout << "Quotient: " << quot << std::endl;
c1++; // Prefix ++
std::cout << "Pre-increment c1: " << c1 << std::endl;
c1--; // Prefix --
std::cout << "Pre-decrement c1: " << c1 << std::endl;
Complex c3 = c1++; // Postfix ++
std::cout << "Post-increment c1: " << c1 << " (previous value: " << c3 << ")" << std::endl;
c3 = c1--; // Postfix --
std::cout << "Post-decrement c1: " << c1 << " (previous value: " << c3 << ")" << std::endl;
return 0;
}
Operator Overloading
Operator overloading is a powerful feature in C++ that allows programmers to define the behavior of existing operators for custom types (usually classes or structs). Through operator overloading, you can make your types use standard operators just like built-in types.
Overloading Rules
- Cannot create new operators: Only existing operators can be overloaded.
- Cannot change the precedence and associativity of operators.
- At least one operand must be a user-defined type.
- Overloaded operators must be class member functions or friend functions.
- The assignment operator and compound assignment operators must be overloaded as member functions.
Overloading Methods
- As a member function: If the operator overload does not need to access another object, it can be overloaded as a member function.
- As a friend function: If the operator overload needs to access two objects, it is usually overloaded as a friend function.
Let’s illustrate how to overload the addition operator + and the subscript operator [] with a simple example.
Overloading the Addition Operator
#include <iostream>
#include <string>
class Vector {
public:
Vector(int size) : size(size), data(new int[size]) {
for (int i = 0; i < size; ++i) {
data[i] = i;
}
}
// Overload addition operator
Vector operator+(const Vector& other) const {
if (size != other.size) {
throw std::runtime_error("Vector sizes must be the same");
}
Vector result(size);
for (int i = 0; i < size; ++i) {
result.data[i] = data[i] + other.data[i];
}
return result;
}
// Overload subscript operator
int operator[](int index) const {
if (index < 0 || index >= size) {
throw std::out_of_range("Index out of bounds");
}
return data[index];
}
~Vector() {
delete[] data;
}
private:
int size;
int* data;
};
// Print vector
void printVector(const Vector& v) {
for (int i = 0; i < v.size; ++i) {
std::cout << v[i] << " ";
}
std::cout << std::endl;
}
int main() {
Vector v1(5);
Vector v2(5);
Vector sum = v1 + v2;
std::cout << "v1: ";
printVector(v1);
std::cout << "v2: ";
printVector(v2);
std::cout << "Sum: ";
printVector(sum);
return 0;
}
Overloading the Subscript Operator
In the code above, we have overloaded the subscript operator []. This operator allows us to access objects of the Vector class like arrays.
Notes
- Efficiency: When overloading operators, pay attention to efficiency issues, such as avoiding unnecessary copies.
- Exception safety: Ensure proper handling of exceptions when overloading operators to avoid memory leaks or other issues.
- Consistency: Ensure that the behavior of overloaded operators is consistent with expectations, especially for compound assignment operators.
Friends
In C++, a friend is a special relationship that allows a function or class to access the private and protected members of another class. The friend relationship is not reciprocal, meaning that if class A is a friend of class B, class B is not necessarily a friend of class A.
Uses
- Access control: Friends can be used to break encapsulation, allowing specific functions or classes to access private members.
- Implementation details: Friend functions can be used to implement class details that are not intended to be part of the public interface.
- Generality: Friends can be used to implement generic operations, such as overloading stream operators
<<and>>.
Definition
- Friend function: A function can be declared as a friend using the
friendkeyword in the class declaration. - Friend class: A class can be declared as a friend of another class, meaning all member functions of the friend class can access the private and protected members of the other class.
Example Code
Below are several examples illustrating how to use friends.
Friend Function
#include <iostream>
class MyClass {
public:
MyClass(int value) : _value(value) {}
friend void printValue(const MyClass& obj); // Declare friend function
private:
int _value;
};
// Friend function implementation
void printValue(const MyClass& obj) {
std::cout << "Value: " << obj._value << std::endl;
}
int main() {
MyClass myObj(42);
printValue(myObj); // Can access private member of MyClass
return 0;
}
Friend Class
#include <iostream>
class Data {
public:
Data(int value) : _value(value) {}
friend class Accessor; // Declare Accessor as friend class
private:
int _value;
};
class Accessor {
public:
void printValue(const Data& data) {
std::cout << "Value: " << data._value << std::endl;
}
};
int main() {
Data myData(100);
Accessor accessor;
accessor.printValue(myData); // Can access private member of Data
return 0;
}
Overloading Stream Operators
#include <iostream>
#include <iomanip>
class Complex {
public:
Complex(double real, double imag) : _real(real), _imag(imag) {}
friend std::ostream& operator<<(std::ostream& os, const Complex& c); // Overload output operator
private:
double _real;
double _imag;
};
// Overload output operator
std::ostream& operator<<(std::ostream& os, const Complex& c) {
os << std::fixed << std::setprecision(2) << c._real << " + " << c._imag << "i";
return os;
}
int main() {
Complex c(3.14, 2.71);
std::cout << "Complex number: " << c << std::endl;
return 0;
}
Notes
- Encapsulation: Using friends breaks encapsulation, so use them cautiously.
- Name conflicts: If multiple classes declare the same function as a friend, it may lead to name conflicts.
- Reciprocity: The friend relationship is not reciprocal; if class A is a friend of class B, class B is not necessarily a friend of class A.
- Template friends: Declaring friends in template classes requires special attention, usually needing explicit template parameter specification.
User-Defined Conversions
In C++, user-defined conversions allow you to define how one type is converted to another. This can be achieved by defining conversion constructors or conversion functions. User-defined conversions can be implicit (no explicit conversion expression needed) or explicit (requiring an explicit conversion expression).
Conversion Constructors
A conversion constructor is a special constructor that takes a single parameter and is not explicitly marked as explicit. Such constructors can be used to convert values of other types to instances of the class.
Explicit Conversion Constructors
If a conversion constructor is marked as explicit, it can only be called through an explicit conversion expression and cannot be used for implicit conversions.
Conversion Functions
In addition to conversion constructors, conversion functions can be defined to perform type conversions. A conversion function is typically a member function with a return type of the target type and no parameters.
Example Code
Below are several examples illustrating how to use user-defined conversions.
Implicit Conversion Constructor
#include <iostream>
class IntegerWrapper {
public:
IntegerWrapper(int value) : _value(value) {} // Implicit conversion constructor
int getValue() const { return _value; }
private:
int _value;
};
int main() {
IntegerWrapper iw(42);
int x = iw; // Implicit conversion
std::cout << "iw: " << iw.getValue() << std::endl;
std::cout << "x: " << x << std::endl;
return 0;
}
Explicit Conversion Constructor
#include <iostream>
class IntegerWrapper {
public:
explicit IntegerWrapper(int value) : _value(value) {} // Explicit conversion constructor
int getValue() const { return _value; }
private:
int _value;
};
int main() {
IntegerWrapper iw(42);
// int x = iw; // Error: Requires explicit conversion
int y = static_cast<int>(iw); // Explicit conversion
std::cout << "iw: " << iw.getValue() << std::endl;
std::cout << "y: " << y << std::endl;
return 0;
}
Conversion Function
#include <iostream>
class IntegerWrapper {
public:
IntegerWrapper(int value) : _value(value) {}
operator int() const { return _value; } // Conversion function
private:
int _value;
};
int main() {
IntegerWrapper iw(42);
int x = iw; // Implicit conversion
std::cout << "iw: " << iw.getValue() << std::endl;
std::cout << "x: " << x << std::endl;
return 0;
}
// Implement getValue member function
int IntegerWrapper::getValue() const {
return _value;
}
Notes
- Implicit conversions: Implicit conversion constructors may lead to unexpected type conversions, especially during function argument passing. Therefore, unless necessary, it is best to use explicit conversion constructors.
- Explicit conversions: Explicit conversion constructors require users to explicitly perform type conversions, which helps avoid unexpected type conversions.
- Conversion functions: Conversion functions can be used to perform more complex conversion logic, but care must be taken to avoid confusion.
Overload Resolution and Member Functions
C++ Member Function Overloading
Member function overloading refers to defining multiple functions with the same name in the same class, but these functions must have different parameter lists. This allows methods in a class to have the same name but exhibit different behaviors based on different parameter types or counts. Overloaded member functions can be selected based on the types and number of arguments passed.
Member Function Overloading Example
#include <iostream>
class MyClass {
public:
void myFunction(int a) { std::cout << "myFunction with int: " << a << std::endl; }
void myFunction(double a) { std::cout << "myFunction with double: " << a << std::endl; }
void myFunction(int a, int b) { std::cout << "myFunction with two ints: " << a << ", " << b << std::endl; }
};
int main() {
MyClass obj;
obj.myFunction(10); // Calls the first myFunction
obj.myFunction(3.14); // Calls the second myFunction
obj.myFunction(5, 6); // Calls the third myFunction
return 0;
}
In this example, MyClass defines three overloaded myFunction member functions, accepting one integer, one floating-point number, and two integers as parameters, respectively. When calling these functions, the C++ compiler automatically selects the correct function version based on the types and number of arguments passed.
Notes on Member Function Overloading
- Parameter lists must differ, including the number, types, or order of parameters.
- Return types cannot be used to distinguish overloaded functions.
- Function bodies can be completely different.
- Can include virtual functions, const member functions, etc.
C++ Operator Overloading
Operator overloading is a feature in C++ that allows you to define the behavior of built-in operators for custom types. You can implement operator overloading through member functions or friend functions.
Operator Overloading Example
Suppose we have a Complex class representing complex numbers; we can overload the addition operator +:
#include <iostream>
class Complex {
public:
Complex(double real, double imag) : realPart(real), imagPart(imag) {}
// Overload addition operator
Complex operator+(const Complex& other) const {
return Complex(realPart + other.realPart, imagPart + other.imagPart);
}
void print() const {
std::cout << "(" << realPart << ", " << imagPart << ")" << std::endl;
}
private:
double realPart;
double imagPart;
};
int main() {
Complex c1(3.0, 4.0);
Complex c2(1.0, 2.0);
Complex c3 = c1 + c2; // Use overloaded operator
c3.print(); // Output (4, 6)
return 0;
}
In this example, the Complex class defines a member function operator+ to overload the addition operator. This function takes a reference to a Complex type as a parameter and returns a new Complex object with the sum of the two complex numbers.
Differences Between Member Function Overloading and Operator Overloading
- Member function overloading refers to defining multiple functions with the same name in the same class, with different parameter lists.
- Operator overloading refers to defining the behavior of built-in operators for custom types, which can be implemented through member functions or friend functions.
Commonalities Between Member Function Overloading and Operator Overloading
- Both aim to improve code readability and maintainability.
- Both rely on the compiler’s polymorphism mechanism to select the correct function.



