-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathItem9.cpp
More file actions
61 lines (51 loc) · 1.07 KB
/
Item9.cpp
File metadata and controls
61 lines (51 loc) · 1.07 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
//Item 9: Never call virtual functions during construction or destruction
#include <iostream>
using namespace std;
class Animal
{
public:
Animal();
virtual void init ( );
};
void Animal::init()
{
cout << "Animal ctor" << endl;
}
Animal::Animal()
{
/* because such calls will never go to a more derived class than that of the
* currently executing constructor or destructor
* Refer notes below for more details.
*/
init ();
}
class Dog : public Animal
{
public:
Dog();
virtual void init ( );
private:
int age;
};
Dog::Dog()
{
}
void Dog::init()
{
age = 0;
cout << "Dog ctor" << endl;
}
int main()
{
Dog d;
}
/* Notes:
* There is a good reason for this counter-intuitive behavior:
* If as expected, virtual functions called during base class construction went down
* to derived classes, the derived class functions would almost certainly refer to
* local data members, but those data members would not yet have been initialized.
*
* Workaround:
* have derived classes pass necessary construction information up to base class
* constructors instead.
*/