473,385 Members | 1,766 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,385 software developers and data experts.

private constructors


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

Apr 18 '06 #1
12 8907
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********@gmail.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>::Instance()
{
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
On 20 Apr 2006 12:49:55 +0200, "Imre Palik"
<fi********************@automation.siemens.com> wrote:
"dan2online" <da********@gmail.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?


One reason you might want to use a singleton is to inherit behaviour
from another class.

Perhaps you want to group a one or more objects into one singleton to
ensure only one instance for a particular program. The classes that
define these objects are not singletons because they can have more
that one instance in other programs.

IMO, it is best to group data and the functions that operate on it in
a class. This takes information hiding a step further by putting the
data and its functionality into class. All access must go through the
class. Not sure what you mean by 'compiler firewall' or how using the
C-style has any advantage over a class singleton in terms of the
compiler.

Clients of a singleton class don't really know or care if the class is
a singleton. It does not impact the interface. Using the C-style
singleton your public interface doesn't need a reference to the object
passed in because you interface knows there's only one instance with
which to work. So someone looking at youi code can tell if a group of
functions operating on some data are operating on only one instance of
that data. The class singleton is better at hiding this fact. But
this is rather subjective in any case.

Tom
Apr 20 '06 #11
godescbach <g.*****************@yahoo.com> writes:
On 20 Apr 2006 12:49:55 +0200, "Imre Palik"
<fi********************@automation.siemens.com> wrote:
"dan2online" <da********@gmail.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?


One reason you might want to use a singleton is to inherit behaviour
from another class.


I'm not sure if it is meaningful to apply the Liskov substitution principle
to singletons. But anyway, you can easily hide the singletonness behind an
ordinary class.

I mean something like this:

// singleton.H
// includes, no need to include the definition of foo here.
struct singleton_interface
{
singleton_interface();
~singleton interface();
void fiddle_with_it();
void set_fubar(fubar fb);
// ...
};

// singleton.C
// includes
static fubar fb_;
static foo bar_;
// other file-scope data

void
singleton_interface::fiddle_with_it()
{
// play with the file scope data
}

void
singleton_interface::set_fubar(fubar fb)
{
fb_ = fb;
}

// other methodes

In this case you have an ordinary C++ class (but w.o. data members), that
still behaves as if it would be a singleton. So if you need a class
because you have to implement a prescribed interface, that is no excuse for
those pesky get_instance() methods ;-)
Perhaps you want to group a one or more objects into one singleton to
ensure only one instance for a particular program. The classes that
define these objects are not singletons because they can have more
that one instance in other programs.
This is simple containment. You can easily take care of it with file scope
data
IMO, it is best to group data and the functions that operate on it in
a class. This takes information hiding a step further by putting the
data and its functionality into class. All access must go through the
class. Not sure what you mean by 'compiler firewall' or how using the
C-style has any advantage over a class singleton in terms of the
compiler.
Even better information hiding :-) That is, being polite, and not showing
the private parts of the class on the interface. With C-style singleton,
you only need the headers defining the types used by the implementation
(i.e., private data), to compile the implementation file. They are totally
unnecessary when compiling user code.
Clients of a singleton class don't really know or care if the class is
a singleton. It does not impact the interface.
You have to get a reference to the singleton from somewhere. This will
lead to lines like this:

newbar = foo:get_instance().fornicate(bar);

I would consider this as an impact on the interface.
Using the C-style
singleton your public interface doesn't need a reference to the object
passed in because you interface knows there's only one instance with
which to work.
This is not necessarily true. Especially if you have the class-like
interface described above, which could be abused to hold an instance ID,
that is used to as an index to e.g., some file local container.
So someone looking at youi code can tell if a group of
functions operating on some data are operating on only one instance of
that data. The class singleton is better at hiding this fact. But
this is rather subjective in any case.


Sorry, but I can't really get this part. Could you explain?

ImRe
Apr 27 '06 #12
>> Can anyone explain to me the exact use of private constructors in c++ ?

Sure. There are a few good uses for declaring a constructor as private.
One of those is being able to tightly control the creation mechanism of
instances of the class (The singleton pattern is a specific example of
this).

Using another example, let's say you have a class that is only able to
use a particular memory allocation algorithm. You could declare the
constructor as private and provide a static "create" method on the
class (which is still able to call the private constructor) that
handles creating an instance of your class using that special
allocation method. All clients of the class would only be able to
create the object through this static function and wouldn't be able to
create an instance on the normal stack or heap, thereby limiting their
chances of misusing the class.

Hope that answers your question.

Lyell

Apr 27 '06 #13

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

Similar topics

3
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...
8
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...
34
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...
10
by: Ioannis Vranos | last post by:
May someone explain why does this compile? class HiddenSealBaseClass { public: HiddenSealBaseClass() { } }; class Sealed: virtual HiddenSealBaseClass
6
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...
2
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...
3
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...
23
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....
0
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....
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
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: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
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...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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...

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.