Humam Helfawi February 2016

Is there any diffrence between {} or default in initializing constructor

Is there any difference (no matter how tiny is) between those three methods of defaulting the constructor of a class:

Directly in the header using {}:

//foo.h
class foo{
public:
    foo(){}
}

Directly in the header using default keyword:

//foo.h
class foo{
public:
   foo()=default;
}

In the cpp using {}

//foo.h
class foo{
public:
   foo();
}

//foo.cpp
#include "foo.h"
foo::foo(){}

Answers


TartanLlama February 2016

Yes, there is a difference.

Option 1 and 3 are user-provided. A user-provided constructor is non-trivial, making the class itself non-trivial. This has a few effects on how the class can be handled. It is no longer trivially copyable, so cannot be copied using memcpy and the like. It is also not an aggregate, so cannot be initialized using aggregate-initialization

A fourth option is the following:

//foo.h
class foo{
public:
   foo();
}

//foo.cpp
#include "foo.h"
foo::foo()=default;

Although this may seem analogous to your second example, this is actually user-provided as well.

Functionally, the defaulted constructor does the same thing as your foo(){}, as specified in [class.ctor]/6.

Post Status

Asked in February 2016
Viewed 1,918 times
Voted 6
Answered 1 times

Search




Leave an answer