Intent
- Handles several child classes by using the same parent class pointer.
Explain
If some classes have common features, it is useful to group them in a parent class. By grouping them, they can be handled by an unified pointer, a parent class pointer. This is Liskov Substitution Principle (LSP). Code 1 shows a simple example of LSP.
// 01_C_LSP.cpp
#include <iostream>
#include <vector>
using namespace std;
class BaseClass
{
public:
virtual void foo() = 0;
};
class DerivedClassFirst : public BaseClass
{
public:
virtual void foo() override
// override: It checks foo() exists in a base class or not
{
cout << "Foo for First derived class" << endl;
}
};
class DerivedClassSecond : public BaseClass
{
public:
virtual void foo() override
{
cout << "Foo for Second derived class" << endl;
}
};
int main()
{
vector v;
v.push_back(new DerivedClassFirst);
v.push_back(new DerivedClassSecond);
for (BaseClass* p : v)
{
p->foo();
}
return 0;
}
// Compile: clang++ -std=c++14
// -o 01_C_LSP 01_C_LSP.cpp
Code 1. Liskov Substitution Principle
Foo for First derived class
Foo for Second derived class
Foo for First derived class
Foo for Second derived class
BaseClass is a parent class of DerivedClassFirst and DerivedClassSecond classes. foo() is defined in BaseClass, but DerivedClassFirst and DerivedClassSecond classes override it. However, in main(), a pointer of BaseClass handles both in the same way, p->foo().
Summary
- Several child classes inheriting the same parent is LSP.
- By using LSP, a parent pointer can handle all its child.
COMMENTS