It's relatively frequent, but it's bad style.
If you have a look at the STL, for example, you'll remark that the class that yields const&
or &
to internal state are usually plain containers and only provide this kind of access for what you actually store in them. You have, obviously, no way to modify directly attributes such as size
or the internal nodes of a binary tree.
Providing direct access to elements breaks encapsulation. Not only do you lose all class invariants wrt to those elements, but you also make them part of your API, and therefore cannot change the implementation of the class without also updating all clients.
As far as I am concerned, they are two types of classes in C++:
struct BigBag {
Foo _foo;
Bar _bar;
FooBar _foobar;
};
class MyClass {
public:
explicit MyClass(int a, int b);
int getSomeInfo();
void updateDetails(int a, int b);
private:
// no peeking
};
That is: either it's just a collection of related elements, in which case everything is public and you're done, or there are class invariants and/or you're concerned with its API because there's a lot of client code, in which case you do not expose at all the implementation details.