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