Q:

What is operator overloading?

0

What is operator overloading?

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Answer:

Operator overloading allows you to redefine the functionality of the allowed operators, such as “+”, “-“, “=”, “>>”, “<<“. You can say that operator overloading is similar to function overloading.

Example,

In the below example I am overloading the + operator to add the two objects of the “Test class” and return the result and print the same. If you don’t know the operator overloading.

#include <iostream>
using namespace std;
//class Test
class Test
{
public:
    //constructor
    Test( int data1, int data2 ) : m_data1(data1), m_data2(data2) {}
    //overloaded + operator
    Test operator+( Test &rObj);
    //print the value
    void print( )
    {
        cout << "m_data1 = " << m_data1 <<endl;
        cout << "m_data2 = " << m_data2 << endl;
    }
private:
    //member variables
    int m_data1,m_data2;
};
// Operator overloaded using a member function
Test Test::operator+( Test &rObj )
{
    return Test( m_data1 + rObj.m_data1, m_data2 + rObj.m_data2 );
}
int main()
{
    Test obj1(1,2);
    Test obj2(5,6);
    Test obj3(0,0);
    //adding two object of class Test
    obj3 = obj1 + obj2;
    //print the result of addition
    obj3.print();
    return 0;
}

Output:

m_data1 = 6
m_data2 = 8

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C++ Interview Questions and Answers(2022)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
What is the difference between function overloadin... >>
<< Explain some ways of doing function overloading in...