➕ Customizing Operators & Friend Access
Operator Overloading allows standard C++ operators (+, -, <<, ==) to work directly with custom objects e.g. Complex c3 = c1 + c2;.
🤝 Friend Functions
A .friend function declared inside a class is not a member function, but is granted full authority to inspect and mutate private class members.
💻 Code Example: Complex Number Addition Operator
⊞C++ Source Code (main.cpp)
#include <iostream>
class Complex {
private:
double real, imag;
public:
Complex(double r = 0, double i = 0) : real(r), imag(i) {}
// Overloading + Operator
Complex operator+(const Complex &other) const {
return Complex(real + other.real, imag + other.imag);
}
// Friend stream insertion operator << for direct std::cout printing
friend std::ostream& operator<<(std::ostream &out, const Complex &c) {
out << c.real << " + " << c.imag << "i";
return out;
}
};
int main() {
Complex c1(3.5, 2.5);
Complex c2(1.5, 4.5);
Complex c3 = c1 + c2; // Calls operator+
std::cout << "c1 = " << c1 << std::endl;
std::cout << "c2 = " << c2 << std::endl;
std::cout << "c1 + c2 = " << c3 << std::endl;
return 0;
}
⊞Windows 11 Pro Terminal Execution OutputWindows 11 Pro Verified
⊞Administrator: Windows 11 Pro Command Prompt (g++ GCC 13.2.0)
—□✕
Microsoft Windows [Version 10.0.22631.3007] (Windows 11 Pro x86_64)
(c) Microsoft Corporation. All rights reserved.
C:\Users\Student\CPP_Project>#include <iostream>
C:\Users\Student\CPP_Project> g++ -o main.exe main.cpp
C:\Users\Student\CPP_Project> main.exe
Hello World from C++ on Windows 11 Pro!
[Process exited with code 0 in 0.001 seconds]