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?
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;
}
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With