forked from Fdevmsy/Design_Patterns_in_Modern_Cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
liskov_substitution_principle.cpp
65 lines (54 loc) · 1.38 KB
/
liskov_substitution_principle.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/***
Acknowledagement: This is a lecture note for course https://www.udemy.com/course/patterns-cplusplus/ by
@Dmitri Nesteruk
Title: Liskov Substitution Principle
Task: Objects in a program should be replaceable with instances of their subtypes
w/o altering the correctness of the program
Shiyu Mou
***/
#include <iostream>
class Rectangle
{
protected:
int width, height;
public:
Rectangle(const int width, const int height)
: width{width}, height{height} { }
int get_width() const { return width; }
virtual void set_width(const int width) { this->width = width; }
int get_height() const { return height; }
virtual void set_height(const int height) { this->height = height; }
int area() const { return width * height; }
};
class Square : public Rectangle
{
public:
Square(int size): Rectangle(size,size) {}
void set_width(const int width) override {
this->width = height = width;
}
void set_height(const int height) override {
this->height = width = height;
}
};
struct RectangleFactory
{
static Rectangle create_rectangle(int w, int h);
static Rectangle create_square(int size);
};
void process(Rectangle& r)
{
int w = r.get_width();
r.set_height(10);
std::cout << "expected area = " << (w * 10)
<< ", got " << r.area() << std::endl;
}
int main342342()
{
Rectangle r{ 5,5 };
process(r);
Square s{ 5 };
process(s);
getchar();
return 0;
}