-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvirtual_assigment.cpp
More file actions
112 lines (103 loc) · 2.32 KB
/
virtual_assigment.cpp
File metadata and controls
112 lines (103 loc) · 2.32 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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
#include <typeinfo>
#include <iostream>
#include <tr1/memory>
namespace v_ass {
using namespace std;
class A {
friend ostream& operator<<(ostream& os, const A&);
public:
A(int val = 0): a_m(val) { }
virtual A& operator=(const A& rhs) {
cout << "virtual A& operator=(const A& rhs) called" << endl;
if (this != &rhs) {
a_m = rhs.a_m;
}
return *this;
}
private:
int a_m;
};
class B : public A {
friend ostream& operator<<(ostream& os, const B&);
public:
B(int val = 0): A(val), b_m(val) { }
virtual B& operator=(const A& rhs) {
cout << "virtual B& operator=(const A& rhs) called" << endl;
if (this != &rhs) {
try {
const B& donor = dynamic_cast<const B&>(rhs);
b_m = donor.b_m;
A::operator=(rhs);
}
catch(std::bad_cast& ex) {
cout << "virtual B& operator=(const A& rhs) call failed, different type provided" << endl;
ex;
}
}
return *this;
}
private:
B& operator=(const B& rhs);
int b_m;
};
class C : public A {
friend ostream& operator<<(ostream& os, const C&);
public:
C(int val = 0): A(val), c_m(val) { }
// co-variant return types
virtual C& operator=(const A& rhs) {
cout << "virtual C& operator=(const A& rhs) called" << endl;
if (this != &rhs) {
try {
const C& donor = dynamic_cast<const C&>(rhs);
c_m = donor.c_m;
A::operator=(rhs);
}
catch(std::bad_cast& ex) {
cout << "virtual C& operator=(const A& rhs) call failed, different type provided" << endl;
ex;
}
}
return *this;
}
private:
C& operator=(const C& rhs);
int c_m;
};
ostream& operator<< (ostream& os, const A& s) {
os << "A::a_m = " << s.a_m;
return os;
}
ostream& operator<< (ostream& os, const B& s) {
os << static_cast<const A&>(s) << " B::b_m = " << s.b_m;
return os;
}
ostream& operator<< (ostream& os, const C& s) {
os << static_cast<const A&>(s) << " C::c_m = " << s.c_m;
return os;
}
}
int main(int argc, char** argv) {
using namespace v_ass;
A a(1);
B b(2);
tr1::shared_ptr<A> a_b(new B(3));
tr1::shared_ptr<B> b_b(new B(4));
tr1::shared_ptr<A> a_c(new C(5));
cout << "a = b" << endl;
a = b; // slicing occurs
cout << a << endl;
a = A(1);
cout << "b = a" << endl;
b = a;
cout << b << endl;
cout << "b = *a_b" << endl;
b = *a_b;
cout << b << endl;
//b = *b_b;
cout << "b = *a_c" << endl;
b = *a_c;
cout << "*a_c = b" << endl;
*a_c = b;
return 0;
}