Predict the output of below C++ programs.
Question 1
1 // Assume that integers take 4 bytes.
2 #include<iostream>
3
4 using namespace std;
5
6 class Test
7 {
8 static int i;
9 int j;
10 };
11
12 int Test::i;
13
14 int main()
15 {
16 cout << sizeof(Test);
17 return 0;
18 }
Output: 4 (size of integer)
static data members do not contribute in size of an object. So ‘i’ is not considered in size of Test. Also, all functions (static and non-static both) do not contribute in size.
Question 2
1 #include<iostream>
2 using namespace std;
3
4 class Base1
5 {
6 public:
7 Base1()
8 {
9 cout << "Base1's constructor called" << endl;
10 }
11 };
12
13 class Base2
14 {
15 public:
16 Base2()
17 {
18 cout << "Base2's constructor called" << endl;
19 }
20 };
21
22 class Derived: public Base1, public Base2
23 {
24 public:
25 Derived()
26 {
27 cout << "Derived's constructor called" << endl;
28 }
29 };
30
31 int main()
32 {
33 Derived d;
34 return 0;
35 }
Ouput:
Base1′s constructor called
Base2′s constructor called
Derived’s constructor called
In case of Multiple Inheritance, constructors of base classes are always called in derivation order from left to right and Destructors are called in reverse order.