Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defaulted constructor vs implicit constructor

It's possible that someone has already asked about this but googling for "default", "defaulted", "explicit" and so on doesn't give good results. But anyway.

I already know there are some differences between an explicitly defined default construtor (i.e. without arguments) and an explicitly defined defaulted constructor (i.e. with the keyword default), from here: The new keyword =default in C++11

But what are the differences between an explicitly defined defaulted constructor and implicitly defined one (i.e. when the user doesn't write it at all)?

class A
{
public:
    A() = default;
    // other stuff
};

vs

class A
{
    // other stuff
};

One thing that comes to mind is that when there is a non-default constructor then the user also has to define a default constructor explicitly. But are there any other differences?

Edit: I'm mostly interested in knowing if there's any good reason to write A() = default; instead of just omitting the constructor altogether (assuming it's the only explicitly defined constructor for the class, of course).

like image 632
NPS Avatar asked Oct 18 '22 20:10

NPS


1 Answers

The purpose of = default is to make the implicit definition explicit. Any differences between an implicitly defined version and the explicitly defaulted version are limited to some additional possibilities appearing due to the presence of an explicit declaration.

  1. The implicitly declared/defined constructor is always public, whereas the access control of the explicitly defined defaulted constructor is under your own control.

  2. Defining a defaulted default constructor enables you annotating it with attributes. For example:

    $ cat a.cpp 
    class A
    {
    public:
        [[deprecated]] A() = default;
    };
    
    int main()
    {
        A a;
    }
    
    $ g++ -std=c++14 a.cpp
    a.cpp: In function ‘int main()’:
    a.cpp:9:7: warning: ‘constexpr A::A()’ is deprecated [-Wdeprecated-declarations]
         A a;
           ^
    a.cpp:4:20: note: declared here
         [[deprecated]] A() = default;
                        ^
    
like image 152
Leon Avatar answered Oct 21 '22 04:10

Leon