-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinheritance.cpp
More file actions
93 lines (84 loc) · 2.15 KB
/
inheritance.cpp
File metadata and controls
93 lines (84 loc) · 2.15 KB
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
namespace Data
{
enum Color
{
red,
green,
blue,
purple,
pink,
yellow,
max_type
};
}
class Fruit
{
private:
std::string m_name{};
Data::Color m_color{};
public:
explicit Fruit(const std::string& name, const Data::Color color)
: m_name{name}, m_color{color}
{}
std::string_view getName() const { return m_name; }
std::string_view getColor() const;
friend std::ostream& operator<<(std::ostream& out, const Fruit& fruit)
{
return out << fruit.getName() << ", " << fruit.getColor();
}
};
std::string_view Fruit::getColor() const
{
switch (m_color)
{
case Data::red:
return "Red";
case Data::green:
return "Green";
case Data::blue:
return "Blue";
case Data::pink:
return "Pink";
case Data::purple:
return "Purple";
case Data::yellow:
return "Yellow";
default:
return "None";
}
}
class Apple: public Fruit
{
private:
double m_fiber{};
public:
explicit Apple(const std::string& name, const Data::Color color, const double fiber)
: Fruit{name,color}, m_fiber{fiber}
{}
friend std::ostream& operator<<(std::ostream& out, const Apple& apple)
{
// return out << "Apple(" << apple.getName() << ", " << apple.getColor() << ", " << apple.m_fiber << ")\n";
return out << "Apple(" << static_cast<const Fruit &>(apple) << ", " << apple.m_fiber << ")\n";
// In order to call parent's friend, we need to pretend to be our parent
}
};
class Banana: public Fruit
{
public:
explicit Banana(const std::string& name, const Data::Color color)
: Fruit{name,color}
{}
friend std::ostream& operator<<(std::ostream& out, const Banana& banana)
{
return out << "Banana(" << static_cast<const Fruit &>(banana) << ")\n";
}
};
int main()
{
const Apple a{ "Red delicious", Data::red, 4.2 };
std::cout << a << '\n';
const Banana b{ "Cavendish", Data::yellow};
std::cout << b << '\n';
return 0;
}