Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete the default constructor?

Tags:

c++

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?

like image 474
Max Avatar asked May 06 '12 21:05

Max


People also ask

Can default constructor be deleted?

The implicitly-declared or defaulted default constructor for class T is undefined (until C++11)defined as deleted (since C++11) if any of the following is true: T has a member of reference type without a brace-or-equal initializer.

How do you delete a constructor in Java?

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

How do you block a default constructor?

Create a private default constructor. That's still accessible by members and friends of the class. It's better to just define constructors taking arguments, which will remove the implicit default constructor completely.

What is a deleted constructor?

In another way, = delete means that the compiler will not generate those constructors when declared and this is only allowed on copy constructor and assignment operator. There is also = 0 usage; it means that a function is purely virtual and you cannot instantiate an object from this class.


2 Answers

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.

like image 73
vidit Avatar answered Sep 25 '22 17:09

vidit


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.

like image 42
Edward Strange Avatar answered Sep 25 '22 17:09

Edward Strange