Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in constructors with X() = delete; and private X(); [duplicate]

Let us assume we have a class X and we want wo explicitly forbid, let say the standard constructor. I used for a long time in the Header file:

private:
    X(); // 1.

so, that the contructor was disabled outside the class, so for anybody. But recently I have learned that in C++11 follwoing was recommended:

X() = delete; // 2.

Both would achive my wish to forbid the standard contructor.

But what is the exact difference bewteen them? Why would C++11 recommend the last one? Are there any other flags, signals set in the 2. way?

like image 891
Ralf Wickum Avatar asked Mar 23 '26 06:03

Ralf Wickum


1 Answers

Example 1 was the way to do it before we had = delete which came out in C++11. Now that we have = delete this will completely get rid of the constructor. With making the constructor private you could still use that constructor in a member function where if you try to default an object in a member function with = delete it will be a compiler error.

#include <iostream>

class Foo
{
    Foo();
public:
    static void SomeFunc() { Foo f; }
};

class Bar
{
public:
    Bar() = delete;
    static void SomeFunc() { Bar b; }
};

int main()
{
    Foo::SomeFunc();  // will compile
    Bar::SomeFunc();  // compiler error
}

Live Example

like image 70
NathanOliver Avatar answered Mar 24 '26 20:03

NathanOliver



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!