DigestCPP

Lets Understand With Example

  • Home
  • Design Principal
  • Design Patterns
  • C++ 11 Features
  • C++11 Multithreading
  • Contact Us

Liskov Substitution Principle

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).

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.

Class Diagram:

source code with example:

Output:

Primary Sidebar




DigestCPP © 2023. All rights reserved.

    About Privacy Policy Terms and Conditions Contact Us Disclaimer