Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Must a deleted constructor be private?

class A { public:     A() = default;     A(const A&) = delete; };  class A { public:     A() = default;  private:     A(const A&) = delete; }; 

Are these two definitions always identical to each other in any cases?

like image 994
xmllmx Avatar asked Sep 21 '13 09:09

xmllmx


People also ask

What will happen if you don't make the constructor as private?

If a constructor is declared as private, then its objects are only accessible from within the declared class. You cannot access its objects from outside the constructor class.

Can default constructor be deleted?

If no user-defined constructors are present and the implicitly-declared default constructor is not trivial, the user may still inhibit the automatic generation of an implicitly-defined default constructor by the compiler with the keyword delete .

Can constructor be defined in private?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.

What happens if constructor is private in C++?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class.


1 Answers

They are different only wrt the produced diagnostics. If you make it private, an additional and superfluous access violation is reported:

class A { public:     A() = default; private:     A(const A&) = delete; };  int main() {     A a;     A a2=a; } 

results in the following additional output from GCC 4.8:

main.cpp: In function 'int main()': main.cpp:6:5: error: 'A::A(const A&)' is private      A(const A&) = delete;      ^ main.cpp:12:10: error: within this context      A a2=a;           ^ 

hence my recommendation to always make deleted methods public.

like image 185
Daniel Frey Avatar answered Sep 17 '22 14:09

Daniel Frey