Say I have a class with some const reference member variable and I would like to forbid a certain type of construction. So I would declare the according constructor private. Of course, a constructor must initialise all const reference member variables of the class. Doing so, however, results in odd looking code:
class A {
};
class B {
B(const A& a): host(a) {}
private:
B():host(A()) {} // This is ugly and not needed !!
const A& host;
};
Is there another way to prohibit a certain construction type except than declaring the constructor private? I do not want to let the compiler write a constructor for me.
Simply don’t define this:
That is, the following should do what you want to do:
The idea is if you’ve defined a constructor that takes parameter(s), then the default constructor is not generated by the compiler. That means, instances of the above class cannot be default created!
C++11 solution
In C++11, you can explicity tell the compiler not to generate a particular constructor as:
Not only that. There is more to it, as explained below:
Now the interesting part
You can also selectively disable constructor(s) for selected types which makes
deletemore interesting. Consider this,Object of this class can be created not only with
intargument, but any type which implicitly converts toint. For example,Now suppose, for whatever reason, I don’t want the users of class
Ato create objects withcharorclass B, which fortunately or unfortunately can implicitly convert toint, then you can disable them as:Now here you go:
Online Demo : http://ideone.com/EQl5R
The error messages are very clear: