Can we have a private constructor ?

Answer Posted / arun

#include<iostream>
using namespace std;

class Singleton
{
public:
static Singleton* Instance();
private:
static Singleton* pinstance;
Singleton();
};

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
}

void main()
{
Singleton *p1 = Singleton::Instance();
cout<<p1<<endl;
Singleton *p2 = p1->Instance();
cout<<p2<<endl;
Singleton & ref = * Singleton::Instance();
}

Is This Answer Correct ?    9 Yes 4 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is static in oop?

585


Which language is not a true object oriented programming language?

640


What is polymorphism in oop example?

513


Why do we use inheritance?

628


What is the full form of oops?

607






What are benefits of oop?

637


What is the example of polymorphism?

554


Why do we need polymorphism in c#?

684


can we make game by using c

3417


Why do we use oop?

604


What are the 3 principles of oop?

616


What is encapsulation process?

577


What is polymorphism what are the different types of polymorphism?

563


What is class and object in oops?

609


What is an interface in oop?

592