suppose i have a class engin and i inherit a class car from engin class
class engin
{
public:
engin(int nobofcylinders);
void start();
};
class car:private engin
{
public:
car():e(8){}
void start()
{
e.start();
}
private:
engin e;
};
now the same can be done by the composition, the question is which approch would be best and is mostly used in programming, and why???????
I prefer to think of inheritance as
derived is a kind of base, that basically means public inheritance. In case of private inheritance it more likederived has a base, which IMHO doesn’t sound right, because that’s IMHO the work for composition not inheritance of any kind. So, since private inheritance and composition essentially mean same thing logically, which to choose? With the example you posted, I’d most certainly go for composition. Why? I tend to think of all kinds of inheritance as akind ofrelationship, and with the example you posted, I can’t think of a situation where I could saya car is kind of an engine, it simply isn’t. It’s indeed likea car has an engine, so why would a car inherit from an engine? I see no reason.Now, indeed there are cases where it’s good to have private inheritance, namely
boost::noncopyable, with it’s ctor/dtor being protected, you’d have hard time instantiating it, and indeed since we want our class tohave a noncopyable part, that’s the only way to go.Some style guides (e.g. google c++ style guide) even recommend to never use private inheritance, for reasons similar to what I already written – private inheritance is just a bit confusing.