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

Can we have inheritance without polymorphism?

608


Explain the advantages of inheritance.

670


What is a null tree?

627


Write a c++ program to display pass and fail for three student using static member function

2810


write knight tour problem which is present in datastructure

2160






How does polymorphism work?

635


What is abstraction in oops?

581


What is the difference between a mixin and inheritance?

519


Explain the concepts involved in Object Oriented programming.

629


what are the realtime excercises in C++?

2333


Why do we use inheritance?

628


What are benefits of oop?

631


What is static in oop?

585


What does it mean when someone says I oop?

579


What are the 4 pillars of oop?

666