Register to reply

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

by zeion
Tags: class, compare, objects
Share this thread:
zeion
#1
Mar5-12, 08:03 AM
P: 467
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.
Phys.Org News Partner Science news on Phys.org
Hoverbike drone project for air transport takes off
Earlier Stone Age artifacts found in Northern Cape of South Africa
Study reveals new characteristics of complex oxide surfaces
M Quack
#2
Mar5-12, 08:52 AM
P: 660
you write a member function called "operator=="

http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B
Borek
#3
Mar5-12, 08:54 AM
Admin
Borek's Avatar
P: 23,363
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.

TylerH
#4
Mar5-12, 01:45 PM
P: 737
C++ how to compare two objects of the same class?

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:
class test
{
   public:
   bool operator==(const test &t); // in this method, see if t is equal to *this.
}
zeion
#5
Mar5-12, 05:05 PM
P: 467
Okay I think I got it thanks.


Register to reply

Related Discussions
Comparing class objects Programming & Computer Science 2
Waitlists to get into class at junior college math class ? Academic Guidance 16
How could I call a base class virtual function from the derived class ? (C++) Programming & Computer Science 2
Why does Chern class belong to INTEGER cohomology class? Differential Geometry 41
How does a Physics class differ from an Engineering class? Academic Guidance 38