Can we have a private constructor ?

Answer Posted / arun

1. Yes we can make a constructor private. By implementing
this concept we can create a singleTon class.

2. Suppose we have a static method is a class that is used
to create the object of the class by using private
constructor then that member function is named as "Named
Constructor".

3. Using this named constructor concept we can create
SingleTon class as well as normal class.

Example:
class Singleton
{
public:
static Singleton* Instance();
protected:
Singleton();
Singleton(const Singleton&);
Singleton& operator= (const Singleton&);
private:
static Singleton* pinstance;
};
Singleton* Singleton::pinstance = 0;// initialize pointer
Singleton* Singleton::Instance ()
{
if (pinstance == 0) // is it the first call?
{
pinstance = new Singleton; // create sole instance
}
return pinstance; // address of sole instance
}
Singleton::Singleton()
{
//... perform necessary instance initializations
}
Singleton *p1 = Singleton::Instance();
Singleton *p2 = p1->Instance();
Singleton & ref = * Singleton::Instance();

Is This Answer Correct ?    25 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Why do we use oop?

604


what is the 3 types of system development life cycle

2431


What are the components of marker interface?

600


What is destructor oops?

621


Why is polymorphism important in oop?

629






What is the difference between inheritance and polymorphism?

589


What is constructor overloading in oop?

605


Where is pseudocode used?

563


What is abstraction in oop with example?

644


What is the point of polymorphism?

584


2. Give the different notations for the class.\

1588


What does and I oop mean in text?

620


What are the important components of cohesion?

550


Can enum be null?

585


Why is it so that we can have virtual constructors but we cannot have virtual destructors?

3827