What are the disadvantages of using inheritance as a way of reusing code?
Main disadvantage of using inheritance is that the two classes (base and inherited class) get tightly coupled. This means one cannot be used independent of each other.
Disadvantage: The inheritance relationship is a, tightly coupled relationship , there will be tight bonding between parent and child. If we change code of parent class it will get affects to the all the child classes which is inheriting the parent code.
Implementation inheritance is described as a way to achieve code reuse. This works by defining methods and variables in a class that is then inherited by other classes. Those other classes are said to be derived from the original class, and the original class is said to be their base class.
So, you can reuse code when it can be: Easily extended and adapted for the new application. Ported to different hardware if needed. Shown to be free from defects or problems that affect the reliability, safety, or security of the new application.
Using inheritance to achieve code reuse suffers from the following problems:
You cannot change the reused behaviour at runtime. Inheritance is a compile-time dependency, so if a GameClient
class inherits from TCPSocket
to reuse the connect()
and write()
member functions, it has the TCP functionality hardcoded. You cannot change this at runtime.
You cannot replace the reused behaviour from the outside for the sake of testing. If a GameClient
class inherits from TCPSocket
so that it gets write()
(for writing data to a socket), you cannot exchange this code from the outside. You cannot plug in a different write() function which logs all data which GameClient
wants to write to a file or so.
You are dependant on multiple inheritance for all but the most simple applications. This opens the door for diamond shaped inheritance trees which increase the code complexity a lot.
Preferring composition over inheritance to reuse code avoids all these issues.
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