Abhineet
Abhineet

Reputation: 6637

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?

Upvotes: 5

Views: 270

Answers (7)

Klaim
Klaim

Reputation: 69792

If obj1+obj2 does return an object that have a show() function member, then yes it's possible.

If not, it is not.

So, it depends on the operator+ function that is used here, that depends on both types of obj1 and obj2.

obj1+obj2 is an expression that have a type, the type of the object returned by the operation, like any expression. Now, once the expression is executed, you have this object. But as here you don't associate it to a name (using assignation for example), it is a "temporary", meaning it will be destroyed at the end of the full expression.

So, if the resulting temporary object's type does provide a show() function then you can call it like you did.

If it don't provide a show() function, then you're trying to call a function that don't exists.

So in any case, the compiler will stop you, it will not be a runtime error.

I would be you, I would setup a minimal test project just to play with those principles.

Upvotes: 2

Adam Bowen
Adam Bowen

Reputation: 11240

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;
}

Upvotes: 8

G-71
G-71

Reputation: 3682

No! The result of (obj1+obj2) isn't object. You may overload "=" and use:

obj3 = obj1 + obj2;
obj3.show();

Upvotes: -2

Alok Save
Alok Save

Reputation: 206646

Yes you can use it if you have overloaded the + operator of class A to return an obect of class A.

Upvotes: 2

ckv
ckv

Reputation: 10838

Write an operator overload for + operator and define the operation you want on that.

In the operator overload for + operator just update the logic you want like adding the individual member variables or concatenating the names etc meaningfully based on your use case

Then you can call That new object.Show() function just like an object calling member function.

Upvotes: 1

Šimon T&#243;th
Šimon T&#243;th

Reputation: 36451

Depends on what the result type of obj1+obj2 is and whether .show() is a constant method.

Upvotes: 0

Oswald
Oswald

Reputation: 31685

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.

Upvotes: 2

Related Questions