What is the difference between inside and outside class overloading?
class A{
public:
bool operator==(const A *i){
....
....
}
};
vs
bool operator==(const A *i , const A *j){
....
....
}
First consider this example using your class (reformatted to a style I prefer):
class A
{
public:
auto operator==( A const* p )
-> bool
{
return true; // Whatever.
}
};
auto main()
-> int
{
A u{}, v{};
A const c{};
bool const r1 = (u == &v); // OK but needlessly annoying.
bool const r2 = (c == &v); // !Will not compile.
}
Here
&
.const
, objects that are const
can not be compared.The conventional way to do this is therefore to pass the argument by reference, and to make the method const
:
class B
{
public:
auto operator==( B const& o ) const
-> bool
{
return true; // Whatever.
}
};
auto main()
-> int
{
B u{}, v{};
B const c{};
bool const r1 = (u == v); // OK.
bool const r2 = (c == v); // OK.
}
If you define the comparison outside the class, like this:
class B
{};
auto operator==( B const& u, B const& v )
-> bool
{
return true; // Whatever.
}
auto main()
-> int
{
B u{}, v{};
B const c{};
bool const r1 = (u == v); // OK.
bool const r2 = (c == v); // OK.
}
… then
B
, that conceivably could change in the future.B
.auto operator==( int const u, B const& v )
-> bool
{
return true; // Whatever.
}
If you choose to place these non-member operators inline inside the class definition, via the friend
mechanism (so that they're found via ADL lookup), then you lose the first bullet point's advantage, but you then have all the code relevant for use of the class, within the class definition:
class B
{
public:
friend
auto operator==( B const& u, B const& v )
-> bool
{
return true; // Whatever.
}
friend
auto operator==( int const u, B const& v )
-> bool
{
return true; // Whatever.
}
};
auto main()
-> int
{
B u{}, v{};
B const c{};
bool const r1 = (u == v); // OK.
bool const r2 = (c == v); // OK.
bool const r3 = (42 == v); // OK.
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With