By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
434,825 Members | 2,437 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 434,825 IT Pros & Developers. It's quick & easy.

private constructors

P: n/a

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

Apr 18 '06 #1
Share this Question
Share on Google+
12 Replies


P: n/a
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

P: n/a

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

P: n/a
can a class derive from singleton class ? And, can any number of
instances of that derived class be created ?

Apr 18 '06 #4

P: n/a
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

P: n/a

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

P: n/a
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

P: n/a
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

P: n/a
"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

P: n/a
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

P: n/a
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

P: n/a
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

P: n/a
>> 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 discussion thread is closed

Replies have been disabled for this discussion.