I have a class A that looks like this:
class A {
// A's internal state
public:
void someMethod();
void anotherMethod();
};
I want to use A inside another class B. I don’t want B to be a subtype of A, but I want A‘s public methods to be accessible in some form to B‘s users.
One way to accomplish this is by simply including an instance of A as a public member of B:
class B {
public:
A a;
// other members
};
Another is to have A be a private member of B, and provide wrappers around A‘s public methods:
class B {
A a;
public:
void someMethod(){ a.someMethod(); }
void anotherMethod(){ a.anotherMethod(); }
}
I’d like to know if there’s a “preferred” way of doing this (or even one that might not involve the two alternatives above), or if it’s simply a matter of preference. Thanks.
It really comes down to specifics here I’m afraid.
You’re right in preferring composition over inheritance when inheritance doesn’t make sense. How you implement that depends on whether or not it makes sense to make an instance of
Apublic.Is there any state in
Athat you do not want changed, or functions that you do not wish to be public? Do you wish to perform any pre- or post-pocessing when one ofA‘s functions are called? Do you care is users set your instance ofAto another? You probably do (though you could just make a getter function), so in this case prefer wrapping the functions.Does it make more sense for
Ato be completely public? If so you save time by not writing a bunch of boilerplate code.It really comes down to the semantics of your wrapper class here.