0

Is it possible to use overloaded operator in another class function instead of the main function?

EXAMPLE I have 2 class functions under public:

bool Angle::operator< (Angle& a2){...}
Angle Angle::operator- (Angle a2){...}

I want to use the overloaded operator from the first function in the second one. I want the code in the 2nd function to be something like this:

Angle Angle::operator- (Angle a2)
{
if (*this>=a2)
{...}
else
cout<<"You can't subtract greater angle from a smaller one"<<endl;
}

So, can I do that? And if I can how?

asked Jul 22, 2013 at 0:17
1
  • By overloading operator >= ? Or by switching your code around to use < instead of >=? Commented Jul 22, 2013 at 0:18

2 Answers 2

2

You overloaded the operator < and You used >= in the code. So You needed another overloading function or altering the previous one:

Angle Angle::operator- (Angle a2)
{
if (*this<a2)
cout<<"You can't subtract greater angle from a smaller one"<<endl;
else
{...}
}
answered Jul 22, 2013 at 0:20
Sign up to request clarification or add additional context in comments.

Comments

0

You could write it like this:

Angle Angle::operator- (Angle a2)
{
 if (!((*this) < a2))
 {...}
 else
 cout<<"You can't subtract greater angle from a smaller one"<<endl;
}

>= is equivalent to not < as long as those have been implemented to have the expected meanings.

Short answer is yes, you can definitely call one overloaded operator from another one. In fact, in many cases the normal form for operator implementation is to do it in terms of another. For example, operator!= should often be implemented as return !(*this == other);. But as others have said, you can only use the ones you have actually overloaded. They won't appear on their own.

answered Jul 22, 2013 at 0:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.