Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"When" does the compiler implicitly declare a default constructor?

I know that compiler will generate a default constructor if we don't declare it.

And "when" is the point I got confused.

A:

class Base {};
int main()
{
    return 0;   
}

B:

class Base {};
int main()
{
    Base b;   // Declare a Base object.
    return 0;
}

The A and B difference is only that B declares a real object of Base. At my point, only when we declare a real object and the compiler finds no constructors does it generate a default constructor.

My question is that:

  1. Will code fragment A generate a default constructor of Base?

  2. Does any tool help to check the result? I use Visual Studio 2010, and /d1 reportAllClassLayout seems useless.

like image 672
Mike Hung Avatar asked Jan 12 '23 03:01

Mike Hung


1 Answers

Quoting C++11.

[class.ctor]§5:

A default constructor for a class X is a constructor of class X that can be called without an argument. If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted (8.4).

[class.ctor]§6:

A default constructor that is defaulted and not defined as deleted is implicitly defined when it is odr-used (3.2) to create an object of its class type (1.8) or when it is explicitly defaulted after its first declaration.

This means that it's declared when your class is defined, and defined (as inline) when it's first used in the given translation unit.

In your case, this means that code fragment A will contain a declaration (but not a definition) of the default constructor, while fragment B will contain both.

like image 127
Angew is no longer proud of SO Avatar answered Jan 17 '23 19:01

Angew is no longer proud of SO