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. 4 5038
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*******@Yaho o.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.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.
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*******@Yaho o.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.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.
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
"Sathyaish" <Sa*******@Yaho o.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.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 ValidateCredent ials(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.AddUse r(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("R ALF", "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 This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
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. And i have
things to offer, and to request.
And a lot of ideas, but who needs them....
here's an example (from type_struct.py):
|
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 that they are not mutually exclusive of one another.
The above classification assimilates my knowledge of having used
constructors in both the above manners.
|
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 possible, it will take
a long time, and I really don't care :)
I need to go through all of the types, look for something within each, and
do something with it if it contains what i'm looking for.
So, is it possible to do this enumeration? Let me...
|
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 destructor.
In the managed world I find that I can not use this because destructors (and copy constructors) for value types are not allowed. Of all the restrictions when compiling managed C++ code (and there are many!) this one is one of my pet hates
To...
|
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 constructors (because we do not
allow developers to instantiate them directly).
Because our business objects are instantiated very frequently, the idea of
using reflection sounds like a performance killer (I haven't done any tests
on this, but the...
| |
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 database for the given ID. I could just leave two separate
constructors, or i could just have the default one call the second with a
"-1" as the ID. This means that the initialization of certain fields can be
based on whether my ID is -1 (for lazy...
|
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;
|
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 built-in-like
behavior for objects of class type. That leads to the "necessity" for
the exception machinery so that errors from constructors can be
handled. Is all that complexity worth it just to get built-in-like
behavior from class objects? Maybe a...
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed.
This is as boiled down as I can make it.
Here is my compilation command:
g++-12 -std=c++20 -Wnarrowing bit_field.cpp
Here is the code in...
|
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
| |
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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 presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: conductexam |
last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one.
At the time of converting from word file to html my equations which are in the word document file was convert into image.
Globals.ThisAddIn.Application.ActiveDocument.Select();...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |