Operator Overloading in C++ Programming


Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type. Operator overloading is used to overload or redefines most of the operators available in C++. It is used to perform the operation on the user-defined data type.

This C++ program demonstrates operator overloading using the class Complex, which represents complex numbers with real and imaginary parts.

  • The Complex class has a private data members real and img that store the real and imaginary parts of a complex number, respectively. It also has a default constructor that initializes both real and img to 0, and a parameterized constructor that sets both real and img to the provided values.
  • The Complex class also overloads the + operator using the member function operator+(). The operator+() function takes another Complex object as input and returns a new Complex object that represents the sum of the two complex numbers. The sum is computed by adding the real parts and the imaginary parts of the two complex numbers.
  • In the main() function, the program creates two Complex objects c1 and c2 with the values (2, 5) and (3, 2), respectively. It then creates a third Complex object c3 and assigns it the value of the sum of c1 and c2 using the overloaded + operator. Finally, it calls the print() function to print the value of c3 in the format real + img i.
  • When the program is executed, it prints the value of the sum of the two complex numbers in the format real + img i.

Source Code

/*
    Operator Overloading in C++
    2+5i
    3+2i
    ----
    5+7i
*/
#include<iostream>
using namespace std;
class Complex
{
private:
    int real,img;
public:
    Complex(){ real=0;img=0;}
    Complex(int r,int i){ real=r;img=i;}
    void print()
    {
        cout<<real<<" + "<<img<<"i"<<endl;
    }
 
    Complex operator +(Complex c)
    {
        Complex temp;
        temp.real=real+c.real;//2+3
        temp.img=img+c.img;//5+2
        return temp;
    }
};
int main()
{
    Complex c1(2,5);
    Complex c2(3,2);
    Complex c3;
    c3=c1+c2;
    c3.print();
    return 0;
}
 

Output

5 + 7i
To download raw file Click Here

Program List


Flow Control

IF Statement Examples


Switch Case


Goto Statement


Break and Continue


While Loop


Do While Loop


For Loop


Friend Function in C++


String Examples


Array Examples


Structure Examples


Structure & Pointer Examples


Structure & Functions Examples


Enumeration Examples


Template Examples


Functions


Inheritance Examples

Hierarchical Inheritance


Hybrid Inheritance


Multilevel Inheritance


Multiple Inheritance


Single Level Inheritance


Class and Objects

Constructor Example


Destructor Example


Operator Overloading Example


Operator and Function Example


List of Programs


Pointer Examples


Memory Management Examples


Pointers and Arrays


Virtual Function Examples