Need some help with C++ Operator Overloading

Duwelon

Golden Member
Nov 3, 2004
1,058
0
0
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?

 

dighn

Lifer
Aug 12, 2001
22,820
4
81
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])){...}
 

LeetestUnleet

Senior member
Aug 16, 2002
680
0
0
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.
 

Markbnj

Elite Member <br>Moderator Emeritus
Moderator
Sep 16, 2005
15,682
14
81
www.markbetz.net
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.
 

Duwelon

Golden Member
Nov 3, 2004
1,058
0
0
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.
 

engineereeyore

Platinum Member
Jul 23, 2005
2,070
0
0
class Box
{
public:
float volume;
bool operator>=(Box *arg1, Box *arg2);
}

bool Box::eek: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.