How to delete the default constructor?

Since c++11, you can set constructor = delete. This is useful in conjunction with c++11's brace initialization syntax {}.

For example:

struct foo {
  int a;

  foo() = delete;
  foo(int _a) {
    // working constructor w/ argument
  }
};

foo f{};  // error use of deleted function foo::foo()
foo f{3}; // OK

see https://en.cppreference.com/w/cpp/language/default_constructor#Deleted_implicitly-declared_default_constructor


Sure. Define your own constructor, default or otherwise.

You can also declare it as private so that it's impossible to call. This would, unfortunately, render your class completely unusable unless you provide a static function to call it.


I would say make it private.. something like

class MyClass
{
private:
    MyClass();
}

and no one(from outside the class itself or friend classes) will be able to call the default constructor. Also, then you'll have three options for using the class: either to provide a parameterized constructor or use it as a utility class (one with static functions only) or to create a factory for this type in a friend class.

Tags:

C++