KInd said:
Hello All,
When is nested class more preferable that Inheritance ? I think with proper
inheritance and friend class concept we can get the same flexibility as nested
classes
Any comments ..
Best Regards
KInd
Well, there are a few types of inheritance. And the subject matter is large
and difficult to grasp, especially for beginners. I'd recommend reading
Scott Meyers' book "Effective C++", which does a good job describing the
different inheritance strategies.
(I'm not sure where friend-ship comes into play in regards to inheritance,
though...?)
But for a short (attempt at an) answer:
Any time you use public inheritance, you should make sure that any function
or object that expects a base class object will also be satisfied by a
derived class obejct as well, because the derived class object "is a" base
class object. If you're creating a class that "is a" base class (such as a
math student "is a" student), then inheritance is fine.
If your new class needs to utilize the behavior of the base class, but can't
actually be substituted for a base class object (even if just in one special
case), then layering (using a nested class) is a better approach. That's
referred to as the "is implemented in terms of" relationship.
And of course, the obvious use of layering is for something simple like "a
computer has a cpu", so your computer class would contain a cpu object (or
perhaps a pointer to one, asuming the cpu is replaceable
). That's call
the "has a" relationship.
(I won't even go nto private or protected inheritance.)
Again though, I'd recommend a good read on the subject.
Hope this helps,
-Howard