473,397 Members | 2,084 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,397 software developers and data experts.

Types of constructors

What is a private constructor, and why would a class have one? What are
the other kinds of constructors besides:

(1) public constructors; and
(2) parameterized constructors

And I understand that they are not mutually exclusive of one another.
The above classification assimilates my knowledge of having used
constructors in both the above manners.

Nov 21 '05 #1
4 5026
Private Constructors - The only time I have used them is when I am creating
a class that holds shared members (non-instance).

Public Constructors - are what get used when you create an instance of a
class using the New keyword. This is the code where you init any internal
vars upon startup.

Parameterized Constructors - are used when you want to create an instance of
a class and initialize it with some values upon creation.
"Sathyaish" <Sa*******@Yahoo.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
What is a private constructor, and why would a class have one? What are
the other kinds of constructors besides:

(1) public constructors; and
(2) parameterized constructors

And I understand that they are not mutually exclusive of one another.
The above classification assimilates my knowledge of having used
constructors in both the above manners.

Nov 21 '05 #2
Private constructors are normally used where the class is not meant to be
instantiated such as in class factories or singleton patterns.

HTH
"Sathyaish" <Sa*******@Yahoo.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
What is a private constructor, and why would a class have one? What are
the other kinds of constructors besides:

(1) public constructors; and
(2) parameterized constructors

And I understand that they are not mutually exclusive of one another.
The above classification assimilates my knowledge of having used
constructors in both the above manners.

Nov 21 '05 #3
Sathyaish wrote:
What is a private constructor, and why would a class have one?
A private constructor is a constructor that can only be used from within the
class itself.

This normally makes the class fairly useless as nothing can actually create
instances of it, but it can be used alongside shared class members to make
sure nothing can instantiate the class but still allow the shared class
members to be used.

You could have a class that has one or more private constructors and also
one or more public constructors. This could allow you to pass internal
values to new instances of the class when it is instantiated by other code
residing within the class (by using a private constructor), but still allow
code outside of the class to create further instances (using a public
constructor).
What are the other kinds of constructors besides:

(1) public constructors; and
(2) parameterized constructors
You can also use Friend constructors. These may be called from anywhere with
your assembly, but cannot be seen or called from outside of the assembly.
These can be useful when you have a single object that creates and returns
instances of other objects from within the same assembly.
And I understand that they are not mutually exclusive of one another.


Indeed -- Public, Private and Friend describe the scope of the constructor,
that is, which other sections of code are able to see the constructor.
Parameterised constructors allow values to be passed into the constructors,
regardless of what the constructor's scope is.

I hope that all makes sense,

--

(O) e n o n e
Nov 21 '05 #4

"Sathyaish" <Sa*******@Yahoo.com> wrote in message
news:11**********************@g47g2000cwa.googlegr oups.com...
:
: What is a private constructor, and why would a class have one?
I was playing around once with a web site where I defined a "User"
object which formed the basic security enforcement for the project. I
wanted to ensure that a "User" could not be instantiated with out a
valid ID and password. In this case, I created the following (highly
simplified) class:
Public Class User
Private mUID As String

Private Sub New
End Sub

Public Sub New(UID As String, PWD As String)
If Not ValidateCredentials(UID, PWD) Then
Throw New Exception
Else
mUID = UID
End If
End Sub

End Class
In this way, a consumer of the User class was prevented from creating
an instance of the class without supplying User ID and Password data.
That is, the following was disallowed

Dim U As New User
Instead the consumer had to instantiate the class in this fashion:

Dim U As New User("ID", "PWD")
If the ID/PWD combination could not be validated, the class threw an
exception. Otherwise the class was instantiated and the consumer could
then use this instance to perform what ever task this user had
permission to do.
In order to allow for the creation of a new user with a given ID/PWD
combination, I added the following function to the User class above:
Public Shared Function NewUser(UID As String, _
PWD As String) As User
If Not IsUniqueID(UID) Then
Throw New Exception
Else
Dim U As New User
U.mUID = UID

DataBase.AddUser(UID, PWD)
Return U

End If
End Function
This function first of all ensured that the user ID was unique to the
project. If not, it threw an exception. Otherwise it create a new User
object, updated the mUID member field if that object, added this user to
the database, then returned the instance of the User class to the
caller.
Since this function is declared as "Shared" (static in C#), consumers of
the class didn't have to have an instance of the User class to call it.
This allowed for the following code (assume that user ID "RALF" did not
currently exist in the project):
Public Class MyClass
Public Shared Sub Main

Dim U As User
U = User.NewUser("RALF", "password")

End Sub
End Class
Note that U is not declared as a 'New User'. This is because the empty
constructor is private and would generate a compiler error. Note also
that 'Dim U As New User("RALF", "password")' is also not allowed since
"RALF" is not a valid user id value. Finally, note that the function
call to User.NewUser(... is not made from an instance of the User class
directly. It could be, but it doesn't have to be as this example shows.
If the function did not have the "Shared" keyword in its definition,
that function call would be illegal.
This highlights a few interesting features about classes. First of all,
while the private constructor was not accessible to an object not part
of the User class itself, it was accessible to the member function
NewUser. This allowed that function to create a new instance of the
class without having to supply the ID and password parameters.
Note also that once that a new instance was created by that function,
the function had full access to the new object's private member fields.
What that means is, any object of a given type can view and manipulate
the private (and otherwise inaccessible) member fields of any other
object of that same type. Of course, this will only happen if the class
is coded to do so (as in the example above).
: What are the other kinds of constructors besides:
:
: (1) public constructors; and
: (2) parameterized constructors
:
: And I understand that they are not mutually exclusive of one
: another. The above classification assimilates my knowledge of
: having used constructors in both the above manners.
Ralf
Nov 21 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: svilen | last post by:
hello again. i'm now into using python instead of another language(s) for describing structures of data, including names, structure, type-checks, conversions, value-validations, metadata etc....
4
by: Sathyaish | last post by:
What is a private constructor, and why would a class have one? What are the other kinds of constructors besides: (1) public constructors; and (2) parameterized constructors And I understand...
3
by: Cliff Harris | last post by:
I have an odd question that I'm hoping someone can help with. I simply (or not simply?) need to enumerate through all of the data types in the .Net framework. I do understand that if this is...
5
by: PaulW | last post by:
Personally, I like to use simple abstractions to wrap resources For example consider a class that wraps a resource - say an IntPtr which is allocated in the constructor and deallocated in the...
5
by: Anders Borum | last post by:
Hello! Whilst refactoring an application, I was looking at optimizing a ModelFactory with generics. Unfortunately, the business objects created by the ModelFactory doesn't provide public...
6
by: Steven Livingstone | last post by:
Bit of advice here folks. I am creating a default constructor that just initializes a new instance of my object and a secon constructor that takes an ID and loads an object with data from the...
12
by: Edward Diener | last post by:
Given value class X { public: // Not allowed: X():i(100000),s(10000) { } // Allowed void InitializeDefaults() { i = 100000; s = 10000; } private: int i;
55
by: tonytech08 | last post by:
How valuable is it that class objects behave like built-in types? I appears that the whole "constructor doesn't return a value because they are called by the compiler" thing is to enable...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.