问题
What is the default access of constructor in c++ and why ?
public, private or protected ?
And how do I check it through the code ?
回答1:
If you do not declare a constructor yourself, the compiler will always generate a public
trivial one for you. They will also implicitly create a public copy constuctor and copy assignment operator.
From c++ standard 12.1.5:
If there is no user-declared constructor for class X, a constructor having no parameters is implicitly declared as defaulted. An implicitly-declared default constructor is an inline public member of its class.
12.8.7 and 12.8.11:
If the class definition does not explicitly declare a copy constructor, one is declared implicitly. [...] An implicitly-declared copy/move constructor is an inline public member of its class.
Finally 12.8.18, 12.8.20, 12.8.22:
If the class definition does not explicitly declare a copy assignment operator, one is declared implicitly. [...] If the definition of a class X does not explicitly declare a move assignment operator, one will be implicitly declared [...]. An implicitly-declared copy/move assignment operator is an inline public member of its class.
If you are using c++11
the move constructor will not always be generated. See section 12.8.20 for more information.
回答2:
What is the default access of constructor in C++ and why?
The implicitly generated default constructor, copy constructor, move constructor, copy assignment, move assignment and destructors are all implicitly declared public
for obvious reasons (otherwise by default all types would not be instanciable, copyable, movable and destructible).
If you are to declare your own default constructor, then of course it depends on what kind of visibility you set for it, just like any other member function.
And how do I check it through the code ?
If your default constructor, for the type T
, was declared protected
or private
the following would not compile:
T x;
回答3:
There is not default access to constructors. You decide what the access is when you declare it in the class. If you are talking about the default constructor that is created by the compiler then the C++ standard 12.1.4 has:
[...]An implicitly-declared default constructor is an inline public member of its class.
回答4:
There's no default access for a constructor or any other member. In a class defined with the keyword class
all members are private by default; in a class defined with the keyword struct
they are public by default. That includes the constructor.
来源:https://stackoverflow.com/questions/32235294/what-is-the-default-access-of-constructor-in-c