Default Constructors

时间:2022-04-14 22:03:19

  A constructor without any arguments or with default value for every argument, is said to be default constructor.

  What is the significance of default constructor?

  Will the code be generated for every default constructor?

  Will there be any code inserted by compiler to the user implemented default constructor behind the scenes?

  The compiler will implicitly declare default constructor if not provided by programmer, will define it when in need. Compiler defined default constructor is required to do certain initialization of class internals. It will not touch the data members or plain old data types (aggregates like array, structures, etc…). However, the compiler generates code for default constructor based on situation.

  Consider a class derived from another class with default constructor, or a class containing another class object with default constructor. The compiler needs to insert code to call the default constructors of base class/embedded object.

 1 #include <iostream>
2 using namespace std;
3
4 class Base
5 {
6 public:
7 // compiler "declares" constructor
8 };
9
10 class A
11 {
12 public:
13 // User defined constructor
14 A()
15 {
16 cout << "A Constructor" << endl;
17 }
18
19 // uninitialized
20 int size;
21 };
22
23 class B : public A
24 {
25 // compiler defines default constructor of B, and
26 // inserts stub to call A constructor
27
28 // compiler won't initialize any data of A
29 };
30
31 class C : public A
32 {
33 public:
34 C()
35 {
36 // User defined default constructor of C
37 // Compiler inserts stub to call A's construtor
38 cout << "C Constructor" << endl;
39
40 // compiler won't initialize any data of A
41 }
42 };
43
44 class D
45 {
46 public:
47 D()
48 {
49 // User defined default constructor of D
50 // a - constructor to be called, compiler inserts
51 // stub to call A constructor
52 cout << "D Constructor" << endl;
53
54 // compiler won't initialize any data of 'a'
55 }
56
57 private:
58 A a;
59 };
60
61 int main()
62 {
63 Base base;
64
65 B b;
66 C c;
67 D d;
68
69 return 0;
70 }

  Output:

  A Constructor
  A Constructor
  C Constructor
  A Constructor
  D Constructor

  There are different scenarios in which compiler needs to insert code to ensure some necessary initialization as per language requirement. We will have them in upcoming posts. Our objective is to be aware of C++ internals, not to use them incorrectly.

  Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
  

  转载请注明:http://www.cnblogs.com/iloveyouforever/

  2013-11-26  10:42:04