0

This is my doubt : I have two classes A and B. I can write :

class A: public B  {....}

So an_instance_of_A could use B methods .

But I could write also:

class A {
public:
B instance_B;
}

So an_instance_of_A could use instance_B methods. (that is, B methods).

I can do the same. What is best ? What is fast to compile ? Is it the same ? Thanks.

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
tonnot
  • 435
  • 1
  • 5
  • 17
  • It depends. What are `A` and `B`? Is `A` a `B`? Why does it need to be public? The speed of compilation is not as important as correct design (except in the most extreme circumstances), and good design rarely causes long compilation times. – James McNellis Mar 07 '12 at 07:13
  • 1
    The problem is not using methods but choosing best design for your problem. A pile of books has been written on topics surrounding this. You can start at wikipedia: http://en.wikipedia.org/wiki/Composition_over_inheritance, http://en.wikipedia.org/wiki/Circle-ellipse_problem and continue from there on. – dbrank0 Mar 07 '12 at 07:20
  • possible duplicate of [Prefer composition over inheritance?](http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance) – Billy ONeal Mar 07 '12 at 07:41

3 Answers3

2

you inherit when there is a "is-a" relationship. like between vehicle and car.

You use data member when there is a "contains" or "consist of" type of realtion. like class school consist of class teacher, class student etc

Rohit Vipin Mathews
  • 11,629
  • 15
  • 57
  • 112
0

public inheritance describes an is-a relationship. That is, anything you can do with B you can also do with A.

Public objects are something completely different and not that common. If A may have more than one B then you can not use inheritance, so use composition (member objects). If they should be public or not depends on A and B and how you want to use them.

EDIT, seem this question is a close match duplicate:

Prefer composition over inheritance?

As James said, compile time should not be a high priority when choosing between inheritance or composition except in special case.

Community
  • 1
  • 1
Johan Lundberg
  • 26,184
  • 12
  • 71
  • 97
0

As said before, public inheritance should only be used if A is also a B (e.g. a Worker is also a Person).

Having an object instance inside the class is better for testing and encapsulation as long as it is not public. Please do not expose members as public except for PODs. This creates several problems (e.g. someone can easily break the integrity of your class)

Tobias Langner
  • 10,634
  • 6
  • 46
  • 76