+ 1

In which situation is it useful to have a private constructor for a class?

I wrote a small class using a private constructor: https://code.sololearn.com/ctcZotz7rpMY/#cs Could you please answer my questions in the comments of the program?

11th Jul 2018, 7:56 PM
comupubit
comupubit - avatar
7 Antworten
+ 1
comupubit well maybe not always at the end of the program (that's just the case for smaller ones), as sometimes the garbage collector sees that you have no more references to the class and just deletes it, but yes the only way to control when an object is deleted is to do it manually.
16th Jul 2018, 7:49 AM
hinanawi
hinanawi - avatar
+ 1
the destructor is indeed called in both situations, check again, i'm getting Constructor Constructor Destructor Destructor as my output.
11th Jul 2018, 9:10 PM
hinanawi
hinanawi - avatar
+ 1
comupubit the order isn't what you expected because objects are destroyed at the end of program execution unless manually deleted. also, in VS2017 they aren't called because of the Console.ReadLine() which prevents the program from ending and destroying the objects, if you run the program in non-debug mode you can delete the extra ReadLine() command and see that the objects do indeed get destroyed.
15th Jul 2018, 6:44 PM
hinanawi
hinanawi - avatar
+ 1
@hinanawi: O.K. That makes sense to me. Thank you again!
16th Jul 2018, 8:32 AM
comupubit
comupubit - avatar
0
@hinanawi: Thank you! You were right. The destructor is called twice as it should be. But shouldnt the order be different? Shouldn't the output be like: Constructor Destructor Constructor Destructor Also: The strange thing is: When I run the same program in Visual Studio 2017 the destructor is not called at all. I dont understand why.
15th Jul 2018, 6:16 PM
comupubit
comupubit - avatar
0
I already found out that a private copy-constructor (or a cast-constructor) can indeed be useful in some situations.
15th Jul 2018, 6:19 PM
comupubit
comupubit - avatar
0
@hinanawi: Thank you! I perfectly understood your answer :-) And your answer seems correct to me. So, this means, that the only way to control, when a destructor is called, is to manually delete an object? Otherwise destructors for existing objects are automatically called at the end of the program?
15th Jul 2018, 9:57 PM
comupubit
comupubit - avatar