Hey guys,

I know the title isn't possible, but I'd like to here how you'd do it then.

Suppose we have this code:

Class Foo {public: int x; };

//somewhere in the code..

int main()
    Foo one, two;
    one.x = 10;
    two.x = 20;

    Foo *a = &one;
    Foo *b = &two;

    //We want to compare Foo::x here, not the pointers.
    bool result = a > b;
    return 0;
}

How would you implement this? I've thought about a compare class, as the STL containers do, and ofcourse a compare functions, but I'd like to hear if there are other options, and if you pick compare classes over compare functions and why etc.

Recommended Answers

All 4 Replies

Overload the boolean operator.

>//We want to compare Foo::x here, not the pointers.
>bool result = a > b;

That's a very bad idea (even if it doesn't work). You're trying to change the established behavior of an existing type, which could have unexpected effects elsewhere (like when you want to start working with arrays of Foo). There's a good reason why C++ disallows overloading solely on built-in types.

>if you pick compare classes over compare functions and why
I'd pick a compare class because the phase of the moon is waning. When the phase of the moon is waxing I use functions.

>Overload the boolean operator.
He's comparing pointers, not Foos. Overloading anything in Foo won't have any useful effect, and operators for a pointer type can't be overloaded. Though I'm curious how you expected this suggestion to work. Can you post an example? :)

Shoot, now I have to look at the moon when I'm coding, thanks Narue.

You say it's a bad idea to overload pointers, which I get, but specifically pointers to Foo objects for the > operator, would that really be a bad idea you think?

>but specifically pointers to Foo objects for the > operator,
>would that really be a bad idea you think?

I don't really see how that changes anything. Granted you can't do it, so this is strictly hypothetical. But even if you overloaded the > operator only for pointers to Foo, you would still override the behavior of the pointer comparison in all cases, even the ones where you weren't expecting it. I can easily see a situation where you (or some maintenance programmer down the line) really do want to compare addresses, but end up comparing the objects because the > operator was overloaded to automagically dereference the pointers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.