james raygan
james raygan

Reputation: 701

Operator Overloading (C++)

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?

Upvotes: 0

Views: 111

Answers (2)

Joel
Joel

Reputation: 1145

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.

Upvotes: 0

ggcodes
ggcodes

Reputation: 2899

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

Upvotes: 2

Related Questions