4

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(){}
0

1 Answer 1

6

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks...May I extend my question a bit and ask why (or when) should I make it trivial or non-trivial ?
Choosing to make your class trivial or non-aggregate probably doesn't buy you much unless you really don't want users treating it as such.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.