• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Need some help with C++ Operator Overloading

Duwelon

Golden Member
I understand the concept of operator overloading in a fairly basic way. Lets say I have a simple box class.

class Box
{
public:
float volume;
}

Then I use 'new' to assign my pointer variable called Box two new Box types:

int main()
{
Box* Boxes[2];
Box[0] = new Box;
Box[1] = new Box;

Box[0]->volume = 125.0;
Box[1]->volume = 150.0;

If(Box[0] >= Box[1])
cout << "Box[0] is bigger\n";
else
cout << "Box[1] is bigger\n";
return 0;
}

How do I write an overloaded operator function for my Box class that compares the value of each Box's volume variable, when using a pointer. I know how to do this when I declare a box like this:

Box Box1;
Box Box2;

Is this even possible?

 
It might be possible if you declare a non-member operator (i.e. non-class function that takes in two arguments instead of one), but even if it's possible, it would be very bad form imo. You don't want to confuse operations between pointers and objects. You can always dereference the pointer before comparison e.g. if( *(Box[0]) > *(Box[1])){...}
 
Assuming you can write it for non-pointer applications, it's the same function, just called differently, so instead of (using << as an example, could be done with any other operator too):

====
Box localDefinedBox;

Box *pointerBox;
pointerBox = new Box();

cout << localDefinedBox;
cout << *pointerBox;
====
SHOULD work, but I didn't test it. All you're doing is de-referencing your pointer.
 
Why don't you just dereference the pointer to get the type it points to? I agree with the poster who said it was bad form to compare the pointers, since that has completely different semantics.
 
Originally posted by: dighn
It might be possible if you declare a non-member operator (i.e. non-class function that takes in two arguments instead of one), but even if it's possible, it would be very bad form imo. You don't want to confuse operations between pointers and objects. You can always dereference the pointer before comparison e.g. if( *(Box[0]) > *(Box[1])){...}

Thanks a lot. I should have known to dereference the pointer probably, it's working great.
 
class Box
{
public:
float volume;
bool operator>=(Box *arg1, Box *arg2);
}

bool Box:😱perator>=(Box *arg1, Box *arg2)
{
if (arg1->volume >= arg2->volume)
return true;
else
return false;
}

Your variable Boxes is an array of Box pointers, so you shouldn't need to change your main function. It's been a while, but I believe this should work.
 
Back
Top