comparing objects using pointers

J

jalina

Is the following ok ?


class Color {

private:
Color() {}

public:

static Color red;
static Color green;
static Color blue;
static Color orange;

};

bool operator==(const A& a1, const A& a2)
{
return &a1 == &a2;
}




Basically, I create some global objects (a new Color object can not be
instanciated) and since red, green, blue, orange are distinct, I think
they can be compared using their address.

Is that right ?
 
I

Ivan Vecerina

: Is the following ok ?
:
:
: class Color {
:
: private:
: Color() {}
:
: public:
:
: static Color red;
: static Color green;
: static Color blue;
: static Color orange;
:
: };
:
: bool operator==(const A& a1, const A& a2)
you mean: Color& a1, const Color& a2 );
: {
: return &a1 == &a2;
: }
:
:
:
:
: Basically, I create some global objects (a new Color object can not be
: instanciated) and since red, green, blue, orange are distinct, I think
: they can be compared using their address.
:
: Is that right ?

It will work portably according to the C++ standard: every object
instance is required to have a unique address for the duration
of its lifetime.

This said, if the set of colors is defined at compile time,
wouldn't it be easier to use enum values ?


Ivan
 
F

Fei Liu

jalina said:
Is the following ok ?


class Color {

private:
Color() {}

public:

static Color red;
static Color green;
static Color blue;
static Color orange;

};

bool operator==(const A& a1, const A& a2)
{
return &a1 == &a2;
}




Basically, I create some global objects (a new Color object can not be
instanciated) and since red, green, blue, orange are distinct, I think
they can be compared using their address.

Is that right ?
Yes. But it really depends on what you mean by '=='.
 

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,755
Messages
2,569,534
Members
45,007
Latest member
obedient dusk

Latest Threads

Top