Debugger
Debugger

Reputation: 9488

How to forbid the use of the default constructor in C++?

I don't want to make it possible in my program to create an object without passing arguments to the constructor.

Is there a way?

Upvotes: 36

Views: 44277

Answers (7)

Nick Bane
Nick Bane

Reputation: 21

You could also just declare constructor, but not define it.

class MyClass
{
   MyClass();
}

Upvotes: 0

wkl
wkl

Reputation: 79921

When you declare any other constructor, the compiler will not generate the default constructor for you. If you have specified a default no-argument constructor, you can make it private.

Remember that the compiler can automatically generate each of these 4 member functions for a class.

  • default no argument constructor
  • default destructor
  • copy constructor
  • assignment operator

But it will not generate a default one if you have declared one yourself, i.e., if you declared a constructor yourself, it will not create the default constructor. If you didn't declare any of the other 3 though, the compiler can generate them.

edit: Note that this information applies to C++03, but it is different in C++11 as Matthieu M. mentions in the comments. C++11 also allows for the constructor to be explicitly forbidden. See Offirmo's answer.

Upvotes: 34

Offirmo
Offirmo

Reputation: 19840

While the other answers are true, there is a new technique in C++11 for expressing that : deleted default constructor

It allows forbidding a function without depending on any other trick. It also clearly express your intention in the code.

class X
{ 
public:
    X(int) {}
    X() = delete; // will never be generated
};

int main()
{ 
    X x; // will not compile;
    X y(1); // will compile.
    return 0;
}

Upvotes: 42

Crazy Bear
Crazy Bear

Reputation: 101

The reason why you can create an object without passing arguments to the constructor is that you have a default constructor. A default constructor is a kind of constructor which doesn't have a parameter or all parameters having default values. And if you didn't declare any constructor, the compiler will make one for you. So, the solution is very easy. You can declare a constructor with a parameter without default value, then the compiler won't bother to make the constructor to you.

Upvotes: 3

amit
amit

Reputation: 178451

creating a non empty constructor "cancels" the empty default constructor, so if you don't explicitly also create an empty constructor, no objects will be created without giving arguments.

Upvotes: 1

Jerry Coffin
Jerry Coffin

Reputation: 490148

Define a constructor taking the correct argument(s). This will prevent the compiler from defining a default constructor.

class X { 
public:
   X(int) {}
};

int main(){ 
    X x; // will not compile;
    X y(1); // will compile.
    return 0;
}

Upvotes: 11

Sebastian Negraszus
Sebastian Negraszus

Reputation: 12215

Create a private default constructor.

Upvotes: 1

Related Questions