Operator function for object pointers

K

kenkahn

I define a class "class xxx" with the following operator override:

class xxx {
int xxx::eek:perator==(const xxx &ptr) const;
}

So if I define

xxx A;
xxx B;

I can do stuff like

if (A == B) {};

My question is what if instead I have

xxx *A_ptr = new xxx;
xxx *B_ptr = new xxx;

How do I define the operator override to work on object pointers
instead of by reference.

if (A_Ptr == B_ptr) {}
 
V

Victor Bazarov

kenkahn said:
I define a class "class xxx" with the following operator override:

class xxx {
int xxx::eek:perator==(const xxx &ptr) const;
}

So if I define

xxx A;
xxx B;

I can do stuff like

if (A == B) {};

My question is what if instead I have

xxx *A_ptr = new xxx;
xxx *B_ptr = new xxx;

How do I define the operator override to work on object pointers
instead of by reference.

if (A_Ptr == B_ptr) {}

You cannot redefine operators for built-in types, and pointers are
built-in types.

Do
if (A_Ptr && B_Ptr && *A_Ptr == *B_ptr) {}

V
 
J

Jorgen Grahn

I define a class "class xxx" with the following operator override:

class xxx {
int xxx::eek:perator==(const xxx &ptr) const;
}

Two errors and a very unfortunate name in three lines. You mean

class xxx {
// public and so on ...
bool operator== (const xxx& other) const;
};

/Jorgen
 
J

James Kanze

kenkahn wrote:

[...]
You cannot redefine operators for built-in types, and pointers are
built-in types.

The important point, of course, is that the above expression
already has a defined semantics. With very few exceptions
(unary operator&), you can't change defined semantics.
Do
if (A_Ptr && B_Ptr && *A_Ptr == *B_ptr) {}

if ( A_Ptr == NULL
? B_Ptr == NULL
: B_Ptr != NULL && *A_Ptr == *B_Ptr ) {}

:)

Most of the time, I think I'd go with a function call.

(PS: I'm not saying that your response was wrong. Since he
didn't say what the semantics were supposed to be, we don't
know. Most of the time I'm dealing with pointers, the built-in
semantics are what I want.)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,070
Latest member
BiogenixGummies

Latest Threads

Top