-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathdiamond_problem_virtual_inheritance.cpp
executable file
·72 lines (56 loc) · 1.55 KB
/
diamond_problem_virtual_inheritance.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
66
67
68
69
70
71
72
#include <iostream>
#include <string>
/*
Ref: https://www.sandordargo.com/blog/2020/12/23/virtual-inheritance
base
/ \
superA superB
\ /
child
*/
namespace normalInheritance {
class base {
public:
base() { std::cout << "base constructor" << std::endl; }
};
class superA : public base {
public:
superA() { std::cout << "superA constructor" << std::endl; }
};
class superB : public base {
public:
superB() { std::cout << "superB constructor" << std::endl; }
};
class child : public superA, superB {
public:
child() { std::cout << "child constructor" << std::endl; }
};
} // namespace normalInheritance
namespace virtualInheritance {
class base {
public:
base() { std::cout << "base constructor" << std::endl; }
};
class superA : virtual public base {
public:
superA() { std::cout << "superA constructor" << std::endl; }
};
class superB : virtual public base {
public:
superB() { std::cout << "superB constructor" << std::endl; }
};
class child : public superA, superB {
public:
child() { std::cout << "child constructor" << std::endl; }
};
} // namespace virtualInheritance
int main() {
std::cout << "===============Normal Inheritance===============" << std::endl;
{ normalInheritance::child childObject; }
/*
"virtual" keyword make the classes superA and superB as virtual base classes
to avoid two copies of base in child class.
*/
std::cout << "===============Virtual Inheritance===============" << std::endl;
{ virtualInheritance::child childObject; }
}