Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the default access of constructor in c++

What is the default access of constructor in c++ and why ?

public, private or protected ?

And how do I check it through the code ?

like image 878
Muhammad Qasim Avatar asked Nov 30 '22 00:11

Muhammad Qasim


2 Answers

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.

like image 190
bricklore Avatar answered Dec 04 '22 13:12

bricklore


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;
like image 38
Shoe Avatar answered Dec 04 '22 13:12

Shoe