0

How may I re-enable the default c'tor if I wrote one of my own?

I know that writing a c'tor will disable the default one

  • Just write it again: `MyClass() : member1({}), member2({}) {}` – Aconcagua Nov 22 '20 at 07:44
  • 1
    I would recommend initializing these members as part of the definition of even call another variant of the ctor – JVApen Nov 22 '20 at 07:47
  • Assuming the class is named `MyClass`, in C++11 and later add `MyClass() = default` to the class definition. Before C++11 (or if any bases or members don't have a default constructor) declare a constructor `MyClass()` and define it in a way that initialises all members and base classes to some chosen default value (e.g. using default constructor of every base or members, if there is one). – Peter Nov 22 '20 at 07:49
  • Also see [this question](https://stackoverflow.com/q/4981241/589259). I'll leave it up to C++ devs here to see if it is a dupe or not. – Maarten Bodewes Nov 22 '20 at 07:51
  • @Aconcagua why do you suggest to do it that way instead of using `= default`? – t.niese Nov 22 '20 at 07:56
  • @t.niese Old habits never die… Apart from, this assures correct initialisation of all members if there are primitive types involved – admitted, not fully equivalent to a real default constructor then. If not needed, the 'new' (cannot really say that after almost 10 years...) `= default` is just as fine, of course. – Aconcagua Nov 23 '20 at 08:08

1 Answers1

6

You might implement it as default (or with custom implementation if needed):

struct C
{
    explicit C(int) {} // Disable default constructor

    C() = default; // re-enable it :)
};
Jarod42
  • 203,559
  • 14
  • 181
  • 302