Constructors really do not differ from other member functions in this respect: if they are marked as private , they are not accessible outside the class (for example, in main ). And since you always need to call a constructor when creating an instance, you cannot create an instance of a class object that has only private (i.e., Inaccessible) constructors.
Now, even if you do not declare any constructor yourself, the C ++ compiler will provide certain default constructors and even the default assignment operator = :
- default constructor (without arguments):
Test::Test() - copy constructor (using a reference to an object of a class type):
Test::Test(const Test&) - assignment operator
= : Test& Test::operator =(const Test&)
And this is where private constructors are useful: sometimes you donβt want your class to have all of these implicit implementations, or you donβt want your class to support certain types of behavior, such as assigning a copy or building a copy. In this case, you declare those members which you do not want for your class as private , for example:
class Test { private: Test(Test& init) { }
stakx source share