Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Operator Overloading in C++

I have doubt whether we can do the following or not.

Suppose I have created two instance of class A i.e. obj1 and obj2 and class A has member function show().

Can I use the following?

(obj1+obj2).show()

If yes, how? If no, why it is not possible?

like image 981
Abhineet Avatar asked Dec 12 '22 11:12

Abhineet


2 Answers

Yes it is possible, just implement operator+ for A and have it return a class of type A:

#include <iostream>

class A
{
public:
    explicit A(int v) : value(v) {}

    void show() const { std::cout << value << '\n'; }

    int value;
};

A operator+(const A& lhs, const A& rhs)
{
    A result( lhs.value + rhs.value );
    return result;
}

int main()
{
    A a(1);
    A b(1);

    (a+b).show(); // prints 2!

    return 0;
}
like image 106
Adam Bowen Avatar answered Feb 22 '23 23:02

Adam Bowen


You can do it if you overload the + operator in such a way that it takes two arguments of type A and yields an object that has a method named show.

like image 26
Oswald Avatar answered Feb 23 '23 00:02

Oswald