Private inheritance VS composition.
I'm having a little confusion when to use each. Since private inheritance seals, in a way, the chain on inheritance, given:
class A { private: int z; protected: int y; public: int x; }; class B : private A { /* B's data members and methods */ /* B has access only to A's public and protected */ }; class C : public B { /* can access no fields of B */ };
C
won't be able to use any of B
's fields. When would I use private inheritance, and when would I use composition?
thanks!
Composition offers better test-ability of a class than Inheritance. If one class consists of another class, you can easily construct a Mock Object representing a composed class for the sake of testing.
One more benefit of composition over inheritance is testing scope. Unit testing is easy in composition because we know what all methods we are using from another class. We can mock it up for testing whereas in inheritance we depend heavily on superclass and don't know what all methods of superclass will be used.
Inheritance and composition are two programming techniques developers use to establish relationships between classes and objects. Whereas inheritance derives one class from another, composition defines a class as the sum of its parts.
The main difference between inheritance and composition is in the relationship between objects. Inheritance: “is a.” E.g. The car is a vehicle. Composition: “has a.” E.g. The car has a steering wheel.
This C++ FAQ entry answers your questions aptly.
Replicating it here:
Use composition when you can, private inheritance when you have to.
Normally you don't want to have access to the internals of too many other classes, and private inheritance gives you some of this extra power (and responsibility). But private inheritance isn't evil; it's just more expensive to maintain, since it increases the probability that someone will change something that will break your code.
A legitimate, long-term use for private inheritance is when you want to build a class Fred
that uses code in a class Wilma
, and the code from class Wilma
needs to invoke member functions from your new class, Fred
. In this case, Fred
calls non-virtuals in Wilma
, and Wilma
calls (usually pure virtuals) in itself, which are overridden by Fred
. This would be much harder to do with composition.
class Wilma { protected: void fredCallsWilma() { std::cout << "Wilma::fredCallsWilma()\n"; wilmaCallsFred(); } virtual void wilmaCallsFred() = 0; // A pure virtual function }; class Fred : private Wilma { public: void barney() { std::cout << "Fred::barney()\n"; Wilma::fredCallsWilma(); } protected: virtual void wilmaCallsFred() { std::cout << "Fred::wilmaCallsFred()\n"; } };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With