📘 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 आपको + जैसे operators को अपनी classes के लिए redefine करने देता है।

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;   // overloaded + use करता है
    cout << c.real << "+" << c.imag << "i";   // 3+7i
    return 0;
}
Output:
3+7i

सारांश

  • Objects पर + use करने को class में operator+ (आदि) define करें।
  • Custom types को 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