57

Sometimes I don't want to provide a default constructor, nor do I want the compiler to provide a system default constructor for my class. In C++ 11 I can do thing like:

class MyClass 
{ 
  public: 
    MyClass() = delete; 
};

But currently my lecturer doesn't allow me to do that in my assignment. The question is: prior to C++ 11, is there any way to tell the compiler to stop implicitly provide a default constructor?

4 Answers 4

54

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.

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

1 Comment

Scott Meyers in his book Effective Modern C++ writes, that also you can leave your private constructor without definition. It will help you to protect your default constructor from invoking from friend classes (link error will be thrown).
16

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.

1 Comment

Unusable only if you make all constructors private.
15

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

6 Comments

You are wrong. foo f{} compiles successfully: coliru.stacked-crooked.com/a/03c3c56e3d143aa4
This code snippet does not work at all. See: godbolt.org/z/TMrdW1naf
@anton_rh it depends on your compiler, try the latest gcc/clang
@ZhengQu fixed it, I was missing a constructor that took an argument.
It compiles with clang as well: coliru.stacked-crooked.com/a/94538c19c9fb76a3. The problem with this solution is that it DEPENDS on compiler.
|
-1

Additionally to declaring the default constructor private, you could also throw an exception when somebody tries to call it.

class MyClass
{
  private:
    MyClass() 
    {
      throw [some exception];
    };
}

1 Comment

That Java approach for private constructors raising exceptions is not a good way to go in modern C++

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.