Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit or include? C++

I had a really long post on this and decided it can be summed up much shorter. Canonically speaking, is it better to include a data member inside of a class as opposed to inheriting it? I found I can implement identical functions either way, but don't really know what caveats I should be aware of.

Code example

#include "KClass.h"
class KPC : public KCharacter {
private:
    KClass MyClass;
};

versus

class KClass : public KCharacter {

};

class KPC : public KClass {


};

In the first example, anytime I needed something from the KClass data, I could access it via MyClass->

In the second class, class KPC would just directly access them since it would inherit the data members.

For specifics to my problem I guess I should detail the class' function.

D&D format. Each character has a class which would determine: weapon/armor proficiencies, bonus defenses, special ability i.e. defender has mark.

So to me, it made sense to inherit it. However, is class a more specific PC or is PC a specific kind of class? There are so many PCs in a game that aren't a specific class, actually class should inherit PC on that concept sense it's more 'specialized' form of a PC. So would I want to structure it in a way of KClass : KPC ?

It seemed easier to implement a Has-A at first, but now I'm second guessing it. Hence the reason why I'm here, asking this question.

like image 337
Chemistpp Avatar asked Jun 30 '26 12:06

Chemistpp


2 Answers

Generally speaking, composition is better than inheritance. But it depends on what exactly you want to do. For the most part think:

IS A -> inheritance
HAS A -> composition 

Inherit when you want/need to extend a base class. If you just need to use another class, just have an instance of it with the other class.

Side note, composition and aggregation are basically the same thing. Conceptually slightly different, in code, the same thing.

like image 129
thecoshman Avatar answered Jul 02 '26 01:07

thecoshman


It's a matter of design and what you are trying to model. Scott Meyers' Effective C++ will note that public inheritance (the second example) models 'is-a', whereas composition (the first example) models 'is-implemented-in-terms-of' or 'has-a'. So, for your example, you should decide what role KClass is playing and which of these philosophies makes more sense. Just looking at the names KCharacter, KClass, and KPC, it's hard for me to tell their purposes.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!