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

Click For Summary
In C++, to return a boolean comparison between two object pointers, the equality operator (==) can be used directly to check if the pointers point to the same object. If the goal is to compare the contents of the objects themselves, a custom equality operator must be defined within the class. This involves creating a member function called "operator==" that compares the current object with another instance of the class. The syntax for defining this operator includes declaring it as a public method that takes a reference to another object of the same class and returns a boolean value. The discussion clarifies that pointer comparison will work without a custom operator, but comparing object values requires the implementation of the operator.
zeion
Messages
455
Reaction score
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.
 
Technology news on Phys.org
Code:
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.
 
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:
class test
{
   public:
   bool operator==(const test &t); // in this method, see if t is equal to *this.
}
 
Okay I think I got it thanks.
 
Learn If you want to write code for Python Machine learning, AI Statistics/data analysis Scientific research Web application servers Some microcontrollers JavaScript/Node JS/TypeScript Web sites Web application servers C# Games (Unity) Consumer applications (Windows) Business applications C++ Games (Unreal Engine) Operating systems, device drivers Microcontrollers/embedded systems Consumer applications (Linux) Some more tips: Do not learn C++ (or any other dialect of C) as a...

Similar threads

  • · Replies 35 ·
2
Replies
35
Views
4K
  • · Replies 4 ·
Replies
4
Views
3K
  • · Replies 2 ·
Replies
2
Views
2K
  • · Replies 40 ·
2
Replies
40
Views
4K
  • · Replies 36 ·
2
Replies
36
Views
6K
  • · Replies 5 ·
Replies
5
Views
3K
  • · Replies 31 ·
2
Replies
31
Views
3K
  • · Replies 17 ·
Replies
17
Views
2K
  • · Replies 23 ·
Replies
23
Views
3K
  • · Replies 9 ·
Replies
9
Views
1K