Can you tell me how comparison works, type operator == (arguments)

Viewed 95

I would like to know how to compare two instances, how the skeleton of the method should be and how to recall it in the main.

in the file.h

type operator==(const& className1, const& className2); like that?

in the file.cpp

type operator==(const& className1, const& className2){

..................
}

like that?

How do I call this back in the main.cpp?

2 Answers

operator== is invoked automatically whenever the compiler encounters an expression a == b where a and b are not both primitive types. Also, the return type should generally be bool.

Type operator==(Type,Type) is an example of Operator Overloading. The goal of Operator Overloading is to make code simpler to read. When you call the == operator in main on two arguments of type Type the compiler will use overload resolution to detect that it should use your operator.

Type operator==(Type,Type); // usually in .h file
int main(){
    Type a;
    Type b;
    cout << (a==b) << endl; // calls operator==(Type,Type)
}
Related