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

What is polymorphism used for?

752


What is the highest level of cohesion?

749


What is the difference between encapsulation and polymorphism?

797


What is polymorphism in oops with example?

740


What is object and example?

851


What does and I oop mean in text?

827


design a c++ class for the chess board,provide a c++ class definition for such class(only class definition is required)

6338


What is interface? When and where is it used?

1858


They started with the brief introduction followed by few basic C++ questions on polumorphism, inheritance and then virtual functions. What is polymorphims? How you will access polymorphic functions in C? How virtual function mechanism works?

1597


What is meant by multiple inheritance?

923


What is the main purpose of inheritance law?

911


Write a program to reverse a string using recursive function?

2000


write a code for this:trailer recordId contains a value other than 99, then the file must error with the reason ‘Invalid RECORD_ID’(User Defined Exception).

1865


What is the real life example of polymorphism?

834


i=20;k=0; for(j=1;k-i;k+=j<10?4:3) { cout<

1623