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
What does oop mean in snapchat?
Why is polymorphism important in oop?
Following are the class specifications: class {int a}; class {int b}; Using friend funtion,calculate the max of two objects and display it.
What is for loop and its syntax?
What is the real time example of encapsulation?
what type of questions
What are the benefits of polymorphism?
What is overloading in oops?
What does I oop mean?
What is inheritance write a program to show use of inheritance?
Why we use classes in oop?
What do you mean by overloading?
Why polymorphism is used in oops?
What is difference between pop and oop?
What is polymorphism programming?