Thomas
Thomas

Reputation: 816

Why can I call deleted, private constructor in C++?

class class1
{
private:
    class1() = delete;
public:
    class1(int a) {}
};

class class2
{
    class1 obj;
};

The above compiles with VS2015 update 3. I'm creating a private constructor which is also deleted. One of the two should already create an error message. What am I missing here?

Upvotes: 2

Views: 97

Answers (2)

user7898585
user7898585

Reputation:

What you are forgetting here is that classes are blueprints for objects. When you create class2 with a class1 member inside it, you haven't actually called it. It is just a blueprint, not actual run code. If you try to instantiate class2, you should get an error.

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385114

I'm creating a private constructor which is also deleted.

Nothing wrong with that.

One of the two should already create an error message.

Nope.

Why can I call deleted, private constructor in C++?

You can't, and you didn't.

What am I missing here?

A call.

Nothing in this program tries to instantiate anything, so there is nothing to fail.

Now try either of the following:

int main()
{
    class1 obj;
}
//----
int main()
{
    class2 obj;
}

… and watch the sparks fly.

Upvotes: 8

Related Questions