Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ overload >> operator with different interaction based on which side of >>

I was wondering if it is possible to have overload the C++ >> operator in this way

Account& operator>> (double left, Account &right)
{
    right.deposit(left);
    return right;
}

Account& operator>> (Account &left, double right)
{
    left.withdraw(right);
    return left;
}

I was wondering if the >> operator had this functionality
so I could do something like this

account1 >> 200 >> account2

Which would withdraw 200 from the first account and then deposit it into the second account.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

As described, this is not going to work for the following simple reason:

account1 >> 200 ...

When this gets evaluated this ends up calling the following overload:

Account& operator>> (Account &left, double right)

Your attention is drawn to the fact that this overload returns an Account &. That’s declared right there, in black and white. Let’s keep going:

... >> account2

And now, the left-hand side of this operator>> is now an Account &, what the overload returned. It is not a double anymore. And it needs to be a double in order for the other overload to pick up the slack, and bring it home. That’s how overloaded operators work in C++.

The simplest solution is probably to simply return a double value from the first overload:

double operator>> (Account &left, double right)
{
    left.withdraw(right);
    return right;
}

Now the result of this expression is a double value, which will have a much easier time getting the other overloaded operator>> to come into picture.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading