Reputation: 4349
I have a class with several members. I've so far successfully had no getters in my class which I like because I don't want people exposing the specifics of the class. I then had to compare two objects of this class for equality. I can't think of a way around creating several public getters. I really don't want to do this to keep encapsulation. Is there another way?
class Foo
{
public:
bool Equals( const Foo &other ) const;
private:
bool x;
// lots of other members
};
bool Foo::Equals( const Foo &other ) const
{
// would I have to create and use public function other.GetX()?
}
Upvotes: 3
Views: 373
Reputation: 272497
@0x499602D2 has already given a good answer that explains how to do this.
To add to that, I think the key point you haven't picked up yet is that access specifiers (protected
and private
) apply at the class level, not the instance level. So one instance of a class can access private members of another instance.
Upvotes: 2
Reputation: 96810
You can create your own public equality member operator:
class Foo
{
public:
bool operator ==(Foo const& rhs) const
{
return x == rhs.x;
}
};
Example of use:
Foo a, b;
assert(a == b);
Upvotes: 2