-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice.cpp
55 lines (44 loc) · 1.24 KB
/
slice.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
#include <iostream>
#include <string>
class Employee
{
std::string m_name;
protected:
virtual void print(std::ostream& os) const { os << "Employee: " << get_name() << std::endl; }
public:
Employee(const std::string& name) : m_name(name) {}
const std::string& get_name() const { return m_name; }
friend std::ostream& operator<<(std::ostream& os, const Employee& e)
{
e.print(os);
return os;
}
};
class Manager : public Employee
{
Employee m_assistant;
protected:
void print(std::ostream& os) const override
{
os << "Manager: " << get_name() << std::endl;
os << "Assistant: " << std::endl << "\t" << get_assistant() << std::endl;
}
public:
Manager(const std::string& name, const Employee& assistant)
: Employee(name), m_assistant(assistant)
{}
const Employee& get_assistant() const { return m_assistant; }
};
/// OOP51-CPP. Do not slice derived objects
void bad(Employee e) { std::cout << e; } // diagnostic required
void good(const Employee& e) { std::cout << e; }
int main()
{
Employee coder("Joe Smith");
Employee typist("Bill Jones");
Manager designer("Jane Doe", typist);
bad(coder);
bad(typist);
bad(designer);
good(designer);
}