English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

5 answers

Actually, a constructor is often declared to be a private member.
By declaring a public constructor, what you are choosing to do, is let other people decide how many instances/objects of that class you want to create.

Now, assume that you want to control the number of objects you want to create.

For example, consider the case of notepad versus yahoo messenger. You can create as many notepad objects you want. Simply click on the notepad icon and you get a new notepad open infront of you.

However irrespective of how many times you click on the yahoo messenger icon on the desktop, the same window keeps popping up for you. That means Microsoft wanted you to create multiple objects of notepad but yahoo wanted to allow you only one object of messenger.

They way to do what yahoo has done is keep the constructor private. Create a different public static method which can call the constructor to create a new object. This method can also see if an object has already been created and based on that invoke the old object.

This is the notion of singleton. There are a few other places like factory methods etc where the constructor can be kept private, but more on that later

2006-07-02 17:58:59 · answer #1 · answered by Neil 5 · 0 0

Can A Constructor Be Private

2016-11-14 13:12:13 · answer #2 · answered by Anonymous · 0 0

It will depend on your particular code. For instance, if we need to assure that a class is only called with at least 2 arguments for the constructor, we can put private definitions of the constructors that take no arguments and one or the other in the private section. This assures that since the constructors we don't want are private, they will never be called and the compiler's default copy constructor(s) and will never interfere by being called in an illegal instance. This is used to eliminate any loopholes that may be made by a "loose cannon" default constructor. I hope that this helps explain it.

2006-06-30 05:01:00 · answer #3 · answered by Anonymous · 0 0

Well, you need to provide some public access to create instances since a new is not a egal operation in that case. May be a static accessor as you do in a singleton..

2006-06-30 01:04:07 · answer #4 · answered by voice13 2 · 0 0

usually u do it whn u dont want others to make objects of ur class
this is one way of making a singleton calss along with a public property

2006-06-30 02:34:19 · answer #5 · answered by forumylittleone 1 · 0 0

fedest.com, questions and answers