473,781 Members | 2,335 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 8960
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:

Hi,
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
http://www.parashift.com/c++-faq-lit....html#faq-20.8)
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
{
public:
static T& Instance();
private:
// Disabled functions
Singleton();
Singleton( const Singleton& );
Singleton& operator=( const Singleton& );
Singleton* operator&();
~Singleton();
};

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

class C
{
public:
void DoSomething() {/*...*/}
private:
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
{
protected:
B() { /*...*/ }

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

public:

// 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

3
21393
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
8
1832
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));
34
3116
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
10
2494
by: Ioannis Vranos | last post by:
May someone explain why does this compile? class HiddenSealBaseClass { public: HiddenSealBaseClass() { } }; class Sealed: virtual HiddenSealBaseClass
6
3591
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.
2
7467
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
3
6799
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...
23
2608
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...
0
2048
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...
0
9474
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10306
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, 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...
0
10139
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 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...
0
8961
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, 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...
1
7485
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 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...
0
6727
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();...
0
5504
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3632
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2869
bsmnconsultancy
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.