473,883 Members | 1,681 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

private constructors

Can anyone explain to me the exact use of private constructors in c++ ?

Apr 18 '06 #1
12 8985
Preets ha scritto:
Can anyone explain to me the exact use of private constructors in c++ ?

For example for implement singleton pattern
Apr 18 '06 #2

Preets wrote:
Can anyone explain to me the exact use of private constructors in c++ ?

If you write a singleton class in C++. you will need to play some
tricks make all constructors private, including default, copy and
assignment operators.

Go to http://msdn.microsoft.com/msdnmag/issues/03/02/CQA/
to find an example of singleton class.

Apr 18 '06 #3
can a class derive from singleton class ? And, can any number of
instances of that derived class be created ?

Apr 18 '06 #4
Basic idea is that if you are making constructor private you will not
be able to create object of that class externaly. It is usefull in many
cases. singleton pattern is only one among them...

Apr 18 '06 #5

a class can derive from a singleton class if the singleton's
constructor is protected but if it is private then ? and what about the
number of instances of the derived class ? will that be also one only ?

Apr 18 '06 #6
If the constructor is private then also you can derive with one
technique. You can make the class to be derived as a friend of class
which's constructor is private.

Apr 18 '06 #7
Preets wrote:
can a class derive from singleton class ? And, can any number of
instances of that derived class be created ?

You can check "More effective C++ by Scott Meyers" 'Item 26: Limiting
the number of objects of a class' for a discussion about singletons and
singletons as base classes.

But singleton is only one of the uses of private Constructors (and the
most famous one, I suppose). there are some other uses such as
prohibiting the instantiation of object for a class (if you want to
facilitate only the use of it's static properties) or forcing the use
of what is called the "virtual constructor" pattern.

Apr 18 '06 #8
"dan2online " <da********@gma il.com> writes:

Preets wrote:
Can anyone explain to me the exact use of private constructors in c++ ?

If you write a singleton class in C++. you will need to play some
tricks make all constructors private, including default, copy and
assignment operators.

Could you explain the reasons why would somebody write a singleton class in
C++ instead of using the good old C-style singleton pattern?

The advantages of the C-style singleton (file-local data with public
interface) are better information hiding, and built in compiler firewall.
But what are the advantages of the singleton class?
Apr 20 '06 #9
Preets wrote:
Can anyone explain to me the exact use of private constructors in c++ ?

Besides singletons and the virtual constructor idiom (see
that have already been mentioned, private constructors can be used to
disable the implicitly generated copy constructor (and assignment
operator) if the class is noncopyable. A singleton holder class itself
often uses this feature, e.g.:

template<class T>
class Singleton
static T& Instance();
// Disabled functions
Singleton( const Singleton& );
Singleton& operator=( const Singleton& );
Singleton* operator&();

template<class T>
T& Singleton<T>::I nstance()
static T myObject;
return myObject;

class C
void DoSomething() {/*...*/}
friend class Singleton<C>;
C() {/*...*/}
~C() {/*...*/}

// Disabled functions for singleton usage
C( const C& );
C& operator=( const C& );
C& operator&();

typedef Singleton<C> theC;

void Foo()
theC::Instance( ).DoSomething() ;

Also, a protected constructor can be used to enforce proper
initialization, especially in the case that the constructor needs to
call a virtual function. This is generally superior to forcing the user
to call an Init() function, which can easily be forgotten, leaving the
object uninitialized. This example is drawn from Sutter and
Alexandrescu's _C++ Coding Standards_ (Item 49):

class B // Hierarchy root
B() { /*...*/ }

// Called right after construction
virtual void PostInitialize( ) { /*...*/ }


// Interface for creating objects
template<class T>
static std::auto_ptr<T > Create()
std::auto_ptr<T > p( new T );
p->PostInitialize ();
return p;

// A derived class
class D : public B { /*...*/ };

// Creating an initialized D object
std::auto_ptr<D > p = D::Create<D>();

Cheers! --M

Apr 20 '06 #10

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

Similar topics

by: Rajesh Garg | last post by:
Can we have private constructors and destructors? IF yes what is the use of such constructors or destructors.....in the sense where can these be implemented in a system................. I have an idea that we can have private constructors and destructors but am not able to find a situation where they can be used... Regards RVG rajeshgarg@opussoft.com
by: Bruce | last post by:
OK, this won't compile saying it can't access private members declared in class F. I don't get it and even if I make the entire class public, it still says that. I realize it has something to do with the constructors but not what. Second, I'd like to take the line: // Create an vector of 1000 F objects init'd to 1,1 vector<F> F(1000,F(1,1));
by: Andy | last post by:
1) Is there any use of defining a class with a single constructor declared in private scope? I am not asking a about private copy constructors to always force pass/return by reference. 2) Is this in any way used to create singletons. Can someone say how? Cheers, Andy
by: Ioannis Vranos | last post by:
May someone explain why does this compile? class HiddenSealBaseClass { public: HiddenSealBaseClass() { } }; class Sealed: virtual HiddenSealBaseClass
by: z_learning_tester | last post by:
Quick question- What happens if you have a private class with a public static method? Can you still say the following? Lets say you are making this call from another class, say class2... int myVal = class1.method(); It seems that you should not be able to, after all from class2, you should not be able to see the private class1, so it's public static method is effectively wasted.
by: Doug | last post by:
I am using reflection to read an assembly and I have a class that has only a private constructor. However when I use the following method. Type.GetConstructors(BindFlags.NonPublic); It does not pick up the private constructor. Instead it reads that there are no constructors. How do I use this method to determine there
by: swengtoo | last post by:
In his book "More Effective C++", Scott Meyer suggests in "Item 4" to "Avoid gratuitous default constructors". To summarize his claims against default constructors for "the right classes" he states that: ================== START QUOTE ============= "A default constructor is the C++ way of saying you can get something for nothing. Constructors initialize objects, so default constructors initialize objects without any information from...
by: Ben Voigt | last post by:
I have a POD type with a private destructor. There are a whole hierarchy of derived POD types, all meant to be freed using a public member function Destroy in the base class. I get warning C4624. I read the description, decided that it's exactly what I want, and ignored the warning. Now I'm trying to inherit using a template. Instead of "destructor could not be generated because a base class destructor is inaccessible", I now have an...
by: zman77 | last post by:
EDIT: -- forgot to mention... I am using Visual Studio 2005, on Win XP, on an intel machine Hi. This is my first post, though I've "lurked" for a while because I find these forums very helpful. Ok my problem is the following. I have a class that contains a "MakeByteArray" function. I have many objects of that class. Inside that function, I have a private variable, that is NOT static. It seems that when I put all these objects in...
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: 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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
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: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
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: 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: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
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...

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.