Liskov's Substitution Principle(LSP)

sharanbr's Avatar, Join Date: Aug 2010
Newbie Member

I am not a seasoned C++ programmer but trying to understand some of the OOPS concepts that can be applied to other languages. I am a bit confused with the above principle.

One of the explanation is as below:
"We must make sure that the new derived classes just extend without replacing the functionality of old classes. Otherwise the new classes can produce undesired effects when they are used in existing program modules"

But most of the time, in our derived classes, we actually replace the functionality of the base class. In other words, we specialize. But according to the above rule, we should not be doing that but adding new functionality without replacing existing one.

Have I understood it correctly?
Am I missing something here?

shabbir's Avatar, Join Date: Jul 2004
Go4Expert Founder
We never replace the existing functionality in derived classes but we enhance it.

Lets take a simple example

Class Operation

Where we have addition as method.

Now our addition method can only add integers.

Now we derive a class AdvOperations to perform addition which can add floating numbers.

Now the above definition says we extend it but not replace it and this means we do not start doing subtraction in addition class but get it more advance.
sharanbr's Avatar, Join Date: Aug 2010
Newbie Member
I think you are giving an example where the derived class is adding fresh piece of code (new function in your example). There are occasions where the functions in the base classes need to be overridden to specialize the class. In that case, following this rule becomes easy. Can you give an example?

I am not questioning the LSP but I am only trying to understand how easy or difficult it is in practical situation.
xpi0t0s's Avatar, Join Date: Aug 2004
This isn't a hard and fast rule that must be followed no matter what. It's purely a guideline. The point is that the function should do what is expected; if it doesn't then this means your object model is wrong.