From design point of view why and when we do inheritence in c++.Is there any substitute of doing Inheritence.I mean composition or aggregation. |
You should use inheritance as little as possible.
Beginners apparently (over) use inheritance where composition or aggregation would be more appropriate. Rather than expounding on the matter here, if you Google for "overuse of inheritance" or the like, you will find a number of articles and forum posts about it.
But one of the key principles of object-oriented design is:
Program to an interface, not an implementation. |
(p18,
Design Patterns, Gamma
et al)
Inheritance breaks this rule, as the implentation of a derived class is coupled to that of it's base class. It should be used sparingly, when the penalty of the increased coupling is outweighed by the benefits of a (markedly) simpler implementation.
A special case of inheritance relates to vtable-only ("interface") base classes. Interface inheritance can be used to implement polymorphic behaviour without sharing any of the implementation. (Strictly, speaking we've been talking about inheritance of implementation before.)
In addition to the matter of inheritance (of implementation) versus composition/aggregation, as C++ is a multi-paradigm language, you also have object-oriented verus generic programming (as well as plain old proceedural and even functional programming.)
Returning to the subject of polymprhism, you therefore have a choice between object-oriented, virtual method "subtype" polymorphism and generic template-based "parametric" polymorphism.
And when discussing interfaces, you can also think about binary reuse versus code reuse (and Component Based Development, or CBD.)
Andy
Why should I prefer composition over inheritance?
http://programmers.stackexchange.com/questions/134097/why-should-i-prefer-composition-over-inheritance
Functional-Style Programming in C++
http://msdn.microsoft.com/en-us/magazine/jj553512.aspx
Component-based software engineering
http://en.wikipedia.org/wiki/Component-based_software_engineering
A Realistic Look at Object-Oriented Reuse
http://www.drdobbs.com/a-realistic-look-at-object-oriented-reus/184415594
etc