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

AI Thread 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.
 
Thread 'Is this public key encryption?'
I've tried to intuit public key encryption but never quite managed. But this seems to wrap it up in a bow. This seems to be a very elegant way of transmitting a message publicly that only the sender and receiver can decipher. Is this how PKE works? No, it cant be. In the above case, the requester knows the target's "secret" key - because they have his ID, and therefore knows his birthdate.

Similar threads

Replies
35
Views
4K
Replies
40
Views
4K
Replies
5
Views
3K
Replies
31
Views
3K
Replies
17
Views
2K
Replies
23
Views
2K
Back
Top