Thursday, July 9, 2009

What are the advantages and disadvantages of using inheritance in C++ programming?

The answer can be very long.


In short, your code can become more flexible and reusable and thus more suitable for complicated hierarchical systems.


I can mention two disadvantages here:


- you code will become less readable;


- it will slightly slow down program performance because of vtables growth.

What are the advantages and disadvantages of using inheritance in C++ programming?
People can go crazy with inheritance and code themselves into a corner. Be careful with it.





There are three basic reasons to use inheritance:





1. Specialization - This is where a new class is derived from a base class and it does something more or slightly different form the base class.





2. Generalization - This is used when two or more classes are similar, and the similarties are factored together into a common base class.





3. Interface - This is used when a base class defines an interface, but doesn't implement some (or all) of it.





In all of these cases, there's one important thing to keep in mind. The derived class IS-A type of the base class. This means that anywhere that the base class works, the derived class can be used as well.





Some developers, especially when they are first learning OO, confuse IS-KIND-OF-LIKE with IS-A. When a potentail derived class is kind of like an already existing class, but not quite, don't use inheritance. Use delegation, but that's a whole other topic.
Reply:One obvious advantage is that inheritance prevents you having to set a lot of properties every time you instantiate an object.





One obvious disadvantage is that some times, you don't want an object to inherit certain properties, so you'll have to go back and reset all those properties manually.


No comments:

Post a Comment