When you do not declare a custom constructor, the compiler automatically generates a default constructor. However, this default constructor may be a trivial (useless) constructor, or it may be nontrivial constructor.
As an example,
class Foo { public: int val; Foo* pnext; } void Foo_bar () { foo bar; if (Bar.val | | bar.pnext) // ... do something
The idea was that Foo had a default constructor that could initialize Var and pnext to 0.
actually otherwise
The reason is that the two members are initialized to 0 and are not required by the compiler. That is, the compiler synthesized a default constructor that is trivial constructor, and does not initialize two members.
So under what circumstances will the compiler synthesize nontrivial constructor? Four cases.
1. member Class Object with default constructor
A member object in the class has the default constructor.
class Foo {public: foo (); Foo (int);} class Bar {public: foo foo; Char* str;}
When you create a bar object, you need to call the bar's default constructor. The default constructor that is collectively called requires the ability to invoke the default construct of class Foo to handle Bar::foo.
But it does not produce any code initialization bar::str. As stated earlier, initializing Foo is the compiler's responsibility, and initializing STR is the responsibility of the programmer.
If you want to initialize STR, we define our own constructors:
0;}
At this point the compiler does not synthesize the default constructor for us, so how does the above initialization of Foo work?
The compiler will expand the existing constructors, where the code is placed, before the user code, according to the member OBJECTSD declaration order, sequentially call the necessary default constructors.
Similar to this:
Bar::bar () { foo. Foo::foo (); 0 ;}
2. Base Class with default constructor
A class without any constructors derives from a parent class with default Constructor, so the default constructor for this derived class is nontrivial. It will call the base class's default constructor.
Similar to the previous one, when the designer provides multiple constructors, the compiler expands the existing constructor, calling base class constructor at the very beginning.
3. Class with a virtual function
A) class declares or inherits a virtual function.
B) class derives from an inheritance chain, which has one or more virtual base function.
The following two expansion operations occur during compilation:
1, a virtual function table. Save the virtual functions address of class
2. The vptr in each class object holds the address of class VTBL.
4. Class with a Virtual Base class
Default constructors for the C + + object model