Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why explicitly delete the constructor instead of making it private?

Tags:

c++

When/why would I want to explicitly delete my constructor? Assuming the reason is to prevent its usage, why not just make it private?

class Foo {    public:      Foo() = delete;  }; 
like image 285
ash Avatar asked Dec 01 '12 00:12

ash


People also ask

What happens if constructor is private?

A private constructor in Java is used in restricting object creation. It is a special instance constructor used in static member-only classes. If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.

Why would you make a constructor private?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.

Should I make a constructor private?

You shouldn't make the constructor private. Period. Make it protected, so you can extend the class if you need to.

What happens if we declare constructor as private in C++?

In your code, the program cannot run since you have defined a constructor and it is private. Therefore, in your current code, there is no way to create objects of the class, making the class useless in a sense.


2 Answers

How about:

//deleted constructor class Foo {    public:      Foo() = delete;        public:     static void foo(); };  void Foo::foo() {    Foo f;    //illegal } 

versus

//private constructor class Foo {    private:      Foo() {}        public:     static void foo(); };  void Foo::foo() {    Foo f;    //legal } 

They're basically different things. private tells you that only members of the class can call that method or access that variable (or friends of course). In this case, it's legal for a static method of that class (or any other member) to call a private constructor of a class. This doesn't hold for deleted constructors.

Sample here.

like image 144
Luchian Grigore Avatar answered Oct 13 '22 01:10

Luchian Grigore


why explicitly delete the constructor?

Another reason:
I use delete when I want to assure that a class is called with an initializer. I consider it as a very elegant way to achieve this without runtime checks.

The C++ compiler does this check for you.

class Foo {    public:        Foo() = delete;        Foo(int bar) : m_bar(bar) {};    private:        int m_bar; } 

This - very simplified - code assures that there is no instantiation like this: Foo foo;

like image 32
Peter VARGA Avatar answered Oct 13 '22 01:10

Peter VARGA