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 polymorphism explain its types?

674


Please send ford technologies placement paper 2 my mail id

1652


Why do we use class?

633


Is oop better than procedural?

568


What type of loop is a for loop?

682






How to improve object oriented design skills?

569


What is a class in oop?

596


What is use of overloading?

604


How to handle exception in c++, For example in a functions i am assigning memory to some variables and also in next instructions in am dividing one variable also. If this functions generates a error while allocating memory to those variable and also while dividing the variable if i divide by zero then catch block how it will identify that this error has cone from perticular instruction

1652


What is encapsulation in oops?

534


Can you name some types of inheritance?

637


Why is polymorphism needed?

591


What is encapsulation example?

545


Can you explain polymorphism?

576


What does and I oop mean?

610