C++ Day 25: Operator Overloading
On Day 25 we explore Operator Overloading – a powerful C++ Characteristic that allows you to redefine how operators work for Operator-defined types (classes/objects).
📚 Topics Covered:
🔹 1. what is hustler overloading
operator overloading lets you hand bespoke meanings to c++ operators (like + - == etc) once they are old with objects
🔸 for example:
cpp
copy
edit
Complicated c1(2 3) c2(1 4);
Complicated c3 = c1 + c2; // plant but if + is overloaded
🔹 ii. Overloading Binary Operators (+ - * etc.)
cpp
Copy
Edit
class Complicated {
public:
int real imag;
Complicated(int r = 0 int i = 0) {
real = r;
imag = i;
}
// Overloading the + operator
Complicated operator + (const Complicated& obj) {
return Complicated(real + obj.real imag + obj.imag);
}
void display() {
cout << real << " + " << imag << "i\n";
}
};
✅ Usage:
cpp
Copy
Edit
Complicated a(1 2) b(3 4);
Complicated c = a + b;
c.display(); // 4 + 6i
🔹 3. overloading unary operators (++ -- - etc)
cpp
copy
edit
class anticipate {
public:
int value;
counter(int cardinal = 0) : value(v) {}
// overloading prefix ++
anticipate operator++() {
++value;
take *this;
}
};
🔹 cardinal. Overloading Comparison Operators
cpp
Copy
Edit
class Point {
public:
int x;
Point(int x) : x(x) {}
bool operator == (const Point& other) {
return x == other.x;
}
};
🔹 5. ally run for overloading
if you need to clog associate in nursing hustler that necessarily approach to close members of both operands employ amp ally Role
cpp
copy
edit
class corner {
int length;
public:
box(int l) : length(l) {}
ally corner hustler + (box b1 corner b2);
};
box hustler + (box b1 corner b2) {
take box(b1length + b2length);
}
⚠️ operators you cannot overload:
:: (scope reAnswer)
. (member access)
.* (pointer-to-member)
sizeof typeid ?: alignof etc.
🛠️ practise Task
Make a Fraction class and overload the + and == operators to:
Add two fractions
Compare if two fractions are equal
📌 Summary:
Characteristic Description
Operator Overloading Define custom behavior for operators
Binary operator Takes one parameter (e.g. a + b)
Unary operator Takes no parameters (e.g. ++a)
Friend Role Used for accessing private Information of objects
Not overloadable :: . .* ?: sizeof etc.
Comments
Post a Comment