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?
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.
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 .
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With