Say I have a large class called Root, which has a lot of members & functions:
class Root {
public:
void func1(); // operates on a and b
void func2();
...
private:
A a;
B b;
C c;
...
};
The class Root is getting a bit big so I decide to factor out a few of the member variables and a function into another class:
class AB {
public:
void func1();
...
private:
A a;
B b;
};
Then using composition I can make AB ab a member variable of Root. Root is now a bit smaller / cleaner / more manageable. The question is about the access level of ab after this composition refactor.
Is it OK in this case for ab to be a public member? Any downsides? Public members are generally considered bad design from what I've read. But here the overall encapsulation / exposure hasn't actually changed...the objects a and b are private within AB so are still hidden from the outside.
(Sidenote: the reason why I would like to make ab public is that it allows easier traversing of Root's composition hierarchy. For example in Root's member c I might want to call func1:
void C::foo(Root& root) {
//do some stuff
root.ab.func1();
}
If ab was private then I'd have to define a pass-through function in root.)