+ 2
In C++, when should we use inheritance?
Better said, why would we use inheritance instead of using multiple base classes instead? I assume this concept plays out greatly with larger projects, but with my smaller projects I'm unaware as to when I should implement inheritance.
8 Answers
+ 10
Use it when you find that there's a need to create some thing(s) that shares some similar attributes, and yet each has their own different ways in doing things, or behaviour.
For example dog, cat and human all inherit mammal attributes, but each of these creatures differ in their ways in doing things, and looks.
Inheritance also improves efficiency. For example, we can copy attributes from mammal class directly into dog, cat and human class, but that would mean redundancy, and possibly, inconsistency.
So when we find a need to update the mammal class (e.g. a new attribute found to be added in mammal class), it's more practical to employ inheritance, since by that we only need to update mammal class. Having known that dog, cat and human class inherits from mammal class, changes in mammal class will also reflect in dog, cat and human class.
That is more efficient rather than hustling to update all classes having copies of attributes from mammal class.
+ 7
The most basic programs don't need object orientation.
+ 6
Very well said. Makes a lot of sense now. It's the "IS-A" relationship basically. Triangle IS A shape. Dog IS A mammal. I would just have to make the ruling as to when inheritance is appropriate depending on the project. Thanks to both of you!
+ 6
You still have inheritance (multiple) with multiple base classes.
+ 3
Stephen Matthew If you want to make several 'versions' of one class, it's better to use inheritance as you won't have as much excessive code. The most common use for inheritance is polymorphism.
+ 2
Personally, I haven't found much need for them. Here's an example anyway:
Let's say you have a general class. This general class has general methods. What if you want to use the methods from that class, but use a different class which uses these methods in other ways? If you just modified the general class to work differently, it won't be the same. Inheritance allows you to take on the abilities of one class and use them how you want.
+ 2
Right, but when would I use it? I've made a few programs that I formatted to use inheritance (really simple , kind of pointless stuff) but when would I actually need it? It sounds really useful for larger applications
+ 2
If you think i should have a new class with extra features & including old features then,you can use inheritance