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?

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 {...} } 
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.