I'm studying for my OOP final, and came across a question that has me a bit stumped. The question is "explain why building a Stack class by publicly inheriting a List class is a poor approach. Describe a better solution."
I'm not sure if my answer is right, but is it because of "publicly inheriting..."? And that it would be better to inherit privately instead so that way no class other than Stack would know of the inheritance?
Inheritance allows us to define a class that inherits all the methods and properties from another class. Parent class is the class being inherited from, also called base class. Child class is the class that inherits from another class, also called derived class.
Proper inheritance occurs when the derived class "IS A" specialized type of the base class. Example Cat IS A Animal. Improper inheritance occurs when a class is inherited from merely for code reuse without having any other relationship. Example Cat Inherits from Engine.
Inheritance should only be used when: Both classes are in the same logical domain. The subclass is a proper subtype of the superclass. The superclass's implementation is necessary or appropriate for the subclass.
If a derived class publicly inherits from a base class, the derived class is an instance of the base class, potentially with some extra functionality or overridden functionality. In the case of a stack and a list, a stack isn't a list - it logically doesn't perform list operations like searching, concatenating, reversing, etc. - so inheriting from list would not be a good idea.
You could use private inheritance here, but that's not a particularly elegant solution. Instead, you could just implement stack by having it hold a list as a private data member. This is the reason why you often hear "favor composition (having private data members) over inheritance."
Hope this helps!
Private inheritance is also a bad idea here. The key point is really that a Stack isn't a List. While you could have a list implementation that only supports stack like operations this doesn't follow from the definition of a list.
In general you should always prefer composition over inheritance. Inheritance should, ideally, only be used to introduce runtime polymorphism. (Inheritance can sometimes be used for convenience, but you should limit this as a much as possible as it creates possibly unnecessary coupling to the base class).
Maybe it's about not using inheritance and take advantage of composition instead.
Stack
has an internal list instead of Stack
is a list (which is false: stack is semantically different than a list).
This is because public inheritance affects interface. If Stack publicly inherits List, it will include List interface.
Yes, private inheritance is better approach there. Personally, I prefer using aggregation in such cases.
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