Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

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

  1. Mar 5, 2012 #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?

  2. jcsd
  3. Mar 5, 2012 #2
  4. Mar 5, 2012 #3


    User Avatar

    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.
  5. Mar 5, 2012 #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
       bool operator==(const test &t); // in this method, see if t is equal to *this.
  6. Mar 5, 2012 #5
    Okay I think I got it thanks.
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?

Similar Discussions: C++ how to compare two objects of the same class?
  1. How best to learn C (Replies: 24)

  2. How to go on with C++ (Replies: 8)