📘 Lesson  ·  Lesson 70

Operator Overloading

Operator Overloading

What is Operator Overloading?

💡 Note

Operator overloading lets you redefine operators like + for your own classes.

Example

C++
#include <iostream>
using namespace std;
class Complex {
public:
    int real, imag;
    Complex(int r, int i) : real(r), imag(i) {}
    Complex operator + (Complex c) {
        return Complex(real + c.real, imag + c.imag);
    }
};
int main() {
    Complex a(2,3), b(1,4);
    Complex c = a + b;   // uses overloaded +
    cout << c.real << "+" << c.imag << "i";   // 3+7i
    return 0;
}
Output:
3+7i

Summary

  • Define operator+ (etc.) in your class to use + on objects.
  • Makes custom types behave like built-in types.

Operator Overloading क्या है?

💡 Note

Operator overloading lets you redefine operators like + for your own classes.

Example

C++
#include <iostream>
using namespace std;
class Complex {
public:
    int real, imag;
    Complex(int r, int i) : real(r), imag(i) {}
    Complex operator + (Complex c) {
        return Complex(real + c.real, imag + c.imag);
    }
};
int main() {
    Complex a(2,3), b(1,4);
    Complex c = a + b;   // uses overloaded +
    cout << c.real << "+" << c.imag << "i";   // 3+7i
    return 0;
}
Output:
3+7i

सारांश

  • Define operator+ (etc.) in your class to use + on objects.
  • Makes custom types behave like built-in types.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n

💻 Live Code Editor

Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें. Agar load na ho to naye tab mein kholें.