How to delete the default constructor?

2019-03-11 00:21发布

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?

标签: c++
3条回答
你好瞎i
2楼-- · 2019-03-11 00:47

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.

查看更多
Fickle 薄情
3楼-- · 2019-03-11 00:54

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.

查看更多
一夜七次
4楼-- · 2019-03-11 00:59

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];
    };
}
查看更多
登录 后发表回答