Liskov Substitution Principle means
It states that every derived class must be substitutable for Base class. If it does not work or problem comes then our design is not good or we should not use inheritance in this context. It is also called as LSP (Liskov Substitution Principle).
The Liskov Substitution Principle (LSP) is a fundamental principle of object-oriented programming, which states that objects of a super class should be replaceable with objects of its subclass without affecting the correctness of the program. In other words, a subclass should be able to substitute its parent class without causing any unexpected behaviour.
If Liskov Substitution Principle works then it is well designed inheritance.
If Liskov Substitution Principle does not work and problem comes then:
- We did not use inheritance correctly.
- Our design is not good.
- We should not use the inheritance, we can think about other approach like association, aggregation and composition.
Main purpose of inheritance is to reuse the existing function of Base class, if derived class is not able to use the Base class functions then does not make any sense to inherit a class from it. I would suggest that if we are creating a derived class then we must cross check this principal.
What are the problems that can come, if we call base functionality using derived object:
- Base functionality is breaking (getting compilation or run time error)
- Base functionality is not clear in derived class.
- Base functionality is not logically correct in derived class.
- Lot of Base functionality is unused in derived class.
If we face above problem in inheritance then we should not use the inheritance, we can think about other approach like association, aggregation and composition.
In summary, the Liskov Substitution Principle in C++ ensures that sub classes can be used interchangeably with their base class without causing any unexpected behaviour. This principle promotes code re-usability and flexibility in object-oriented designs.