What are the disadvantages of using inheritance as a way of reusing code?
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.