The default constructor of the C++ object model

When no custom constructor is declared, the compiler automatically generates a default constructor. But this default constructor may be a trivial (useless) constructor, or it may be a nontrivial constructor.

 for example

class Foo {
    public:
        int val;
        Foo* pnext;  
}  

void foo_bar()
{
     Foo bar;
     if(bar.val || bar.pnext)
          //...do something  
} 

The previous idea was that Foo has a default constructor that initializes var and pnext to 0.

actually not.

The reason is that initializing both members to 0 is not what the compiler needs. That is to say, the compiler synthesizes a default constructor that is a trivial constructor, which does not initialize the two members.

So under what circumstances does the compiler synthesize the nontrivial constructor? Four situations.

 

1. Member Class Object with Default Constructor

A member object in a class has a default constructor.

class Foo {
public: 
     Foo();
     Foo(int);
}  

class Bar 
{
public:
     Foo foo;
     char* str;
}

When creating a Bar object, the default constructor of Bar needs to be called. The collective default constructor needs to be able to call the default constructor of Class Foo, dealing with Bar::foo.

But it doesn't generate any code to initialize Bar::str. As said before, it is the compiler's responsibility to initialize foo, and the programmer's responsibility to initialize str.

If in order to initialize str, we define our own constructor:

Bar :: Bar () {str = 0 ;}

At this point, the compiler will not synthesize the default constructor for us, so how does the above initialization foo work?

It turns out that the compiler will expand the existing constructors, insert code in them, and call the necessary default constructors in turn according to the declaration order of member objectsd before the user code.

Something like this:

Barbarian()
{
     foo.Foo::Foo();
     str = 0;
}

 

2. Base Class with Default Constructor

A class without any constructor is derived from a parent class with default c onstructor, then the default constructor of the derived class is nontrivial. It will call the default constructor of the base class.

Similar to the previous one, when the designer provides multiple constructors, the compiler will expand the existing constructors and call the base class constructor at the very beginning.

 

3. Class with a Virtual Function

a) class declares or inherits a virtual function.

b) class is derived from an inheritance chain in which there are one or more virtual base functions.

 

The following two expansion operations occur during compilation:

1. A virtual function table. It stores the virtual functions address of the class

2. The vptr in each class object stores the address of the class vtbl.

 

 

4. Class with a Virtual Base Class

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325299141&siteId=291194637