Drew Drew - 2 months ago 12
C++ Question

Check if two classes are equal (identity)

I have looked at multiple SO questions and forum posts regarding this, but all posts have either related to pointers (not class instances) or checking equivalence (not identity). Right now I'm using the

==
operator on
this
and the variable containing the other class object. It works, but Eclipse is spitting out a warning
no match for operator==(operand types are Class* and Class
Here are the relevant files:

Main.cpp



#include <iostream>
#include "Class.h"
using namespace std;

int main() {
Class a;
Class b;
cout << "Are a & b the same instance? " << a.sameInstance(b) << endl;
return 0;
}


Class.h



#pragma once

class Class {
public:
Class();

bool sameInstance(Class);
};


Class.cpp



#include "Class.h"

Class::Class() {

}

bool Class::sameInstance(Class c) {
return this == c;
}


Edit: I converted to Class pointers:

Updated Class.h



#pragma once

class Class {
public:
Class();

bool sameInstance(Class*);
};


Updated Class.cpp



#include "Class.h"

Class::Class() {

}

bool Class::sameInstance(Class* c) {
return this == c;
}


But I'm not sure how to pass b as a pointer in Main.cpp. Left unchanged, it's giving me the error
Invalid arguments Candidates are bool sameInstance(Class*)


Edit2: I put an & before a variable name to convert it to a pointer. So instead of
a.sameInstance(b)
, it'd be
a.sameInstance(&b)
.

Answer

In your sameInstance method, you must pass the parameter either by reference or by pointer. Passing by value will not work, because the function will be operating on a copy of the object, which is obviously a different instance.

By reference:

bool Class::sameInstance(const Class& c) {
    // Take address of c to get a pointer which can be compared to this
    return this == &c;
}

// main()
cout << "Are a & b the same instance? " << a.sameInstance(b) << endl;

By pointer:

bool Class::sameInstance(const Class* p) {
    // p is already a pointer which can be compared to this
    return this == p;
}

// main()
// Take the address of b to pass to sameInstance()
cout << "Are a & b the same instance? " << a.sameInstance(&b) << endl;

Passing by reference is better idiomatic C++.

In both cases, you should use const, because sameInstance() doesn't modify its parameter.