2

I'm quite new in C++ and I would like to learn good practices from the beginning, so my question explained with an example is:

Having:

class A
{
    int mNumber;
};

If I need to use class A inside class B, what is better?to include an object?

class B
{
    A * mpA;
    int mColor;
};

Or inherit from Class A?

class B : public A
{
    int mColor;
};

Is there any good habit talking in a generally way to do this?

Breikdans
  • 67
  • 6
  • 1
    Ops! sorry, I was looking for it and I couldn't find an answer...thanks! :) – Breikdans Jan 19 '15 at 08:57
  • 1
    The duplicate linked by John certainly explains the composition/inheritance aspect very well. Prefer composition in this case. But I would add to the C++ aspect: don't do `A *mpA`, do `A mA`. The default in C++ is to handle objects as values (which they are) and only resort to dynamic allocation if it's necessary. – Angew is no longer proud of SO Jan 19 '15 at 08:58
  • 1
    @Angew `A*` doesn't imply dynamic allocation. If `B` doesn't own `mpA`, it doesn't make sense to have an object as a member, and a pointer (smart or not) is the way to go. – Luchian Grigore Jan 19 '15 at 09:00
  • 1
    @LuchianGrigore Of course. But given that the OP describes themselves as "quite new" and is considering inheritance, I consider it safe to assume `B` will actually own an `A` and the pointer was going to be an owning one. – Angew is no longer proud of SO Jan 19 '15 at 09:05

1 Answers1

2

Prefer composition over inheritance - however remember that for each particular situation, the other approach might be better.

Composition is:

class A
{
    B b;
};

Inheritence is:

class A : public B
{
};

Use the first when the relationship is "has-a" and the latter when it is "is-a".

Your example is a loose type of composition - if the member is a pointer, it doesn't (necessarily) signify ownership.

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625