C++ how to compare two objects of the same class?

  1. Hi, noob question here,

    In C++, how can I return boolean comparison between two object pointers?
    ie. return True if the pointers point to same object.

    I've tried == but it doesn't work.
    Do I need to define a comparison method from within the class?
    If so what is the syntax for doing it?

    Thanks.
     
  2. jcsd
  3. Borek

    Staff: Mentor

    Code (Text):
    MyClass *p1, *p2;

    if (p1 == p2) printf("The same object");

    if (*p1 == *p2) printf("Identical objects");
    The latter check requires you to define and implement == operator for MyClass.
     
  4. The equality operator will work on pointers regardless of whether you've implemented the equality operator for your class. If it's giving an error when used with pointers, then you're doing something wrong.

    To define the equality operator as part of your class:
    Code (Text):

    class test
    {
       public:
       bool operator==(const test &t); // in this method, see if t is equal to *this.
    }
     
     
  5. Okay I think I got it thanks.
     
Know someone interested in this topic? Share a link to this question via email, Google+, Twitter, or Facebook