Reputation: 1167
Let say I have a class with multiple methods. I like to separate into multiple classes. Can I inherit that classes or can I create member with that classes? Which one is more efficient and usable?
Let's say i have this below class
class ClassRoom {
vector<int> BoysIds;
vector<int> GirlsIds;
public:
void RegisterBoy(int i);
void RegisterGirl(int i);
int GetTotalBoys();
int GetTotalGirls();
};
And i have separated into multiple classes like below
class Boys {
vector<int> BoysIds;
public:
void RegisterBoy(int i);
int GetTotalBoys();
};
class Girls {
vector<int> GirlsIds;
public:
void RegisterGirl(int i);
int GetTotalGirls();
};
inheriting a class is more efficient?
class ClassRoom : public Boys, public Girls {
};
creating a member is more efficient?
class ClassRoom {
public:
Boys m_boys;
Girls m_girls;
};
Upvotes: 4
Views: 1157
Reputation: 26117
Both multiple inheritance and members are efficient. However, it is probably better style to use members here, not multiple inheritance, unless you have a really good reason for it. Just splitting the class up, without any other justification, is probably not a good enough reason to use multiple inheritance.
As a general rule, multiple inheritance should be avoided unless there is a good reason why you need to use it.
Also, in recent decades, having members (your class "has-a" Boys
and a Girls
) is preferred to inheritance (your class "is-a" Boys
and a Girls
) unless there is a good reason to do otherwise.
You can still make your members separate classes, without using multiple inheritance. However, if you want to define your public methods in the separate classes, you will need to forward them manually.
Upvotes: 3