Sams Teach Yourself C in 21 Days

(singke) #1
Working with C++ Classes and Objects 697

BD3


LISTINGB3.9 order.cpp. Constructor and destructor order of operation with inheritance
1: #include <iostream.h>
2:
3: class base {
4: protected:
5: int Bval;
6: public:
7: void set_Bval(int x) { Bval = x; };
8: int get_Bval(int x) { return Bval; };
9: base( int x = -99 );
10: ~base(); //destrutor
11: };
12:
13: class sub : public base {
14: protected:
15: int Sval;
16: public:
17: void set_Sval( int x ) { Sval = x; };
18: int get_Sval() { return Sval; };
19: sub( int x = -22 );
20: ~sub(); // destructor
21: };
22:
23: base::base( int x )
24: {
25: Bval = x;
26: cout << “\n B >> in base class constructor...”;
27: }
28:
29: base::~base()
30: {
31: cout << “\n B >> ...in base class destructor”;
32: }
33:
34: sub::sub( int x ) : base ( -1 )
35: {
36: cout << “\n S >> in sub class constructor...”;
37: }
38:
39: sub::~sub()
40: {
41: cout << “\n S >> ...in sub class destructor”;
42: }
43:
44: int main(int argc, char* argv[])
45: {
46: cout << “\n. >> Instantiating a sub class...\n”;
47:
48: sub sub1;

38 448201x-Bonus3 8/13/02 11:19 AM Page 697

Free download pdf