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
Can we have inheritance without polymorphism?
Explain the advantages of inheritance.
What is a null tree?
Write a c++ program to display pass and fail for three student using static member function
write knight tour problem which is present in datastructure
How does polymorphism work?
What is abstraction in oops?
What is the difference between a mixin and inheritance?
Explain the concepts involved in Object Oriented programming.
what are the realtime excercises in C++?
Why do we use inheritance?
What are benefits of oop?
What is static in oop?
What does it mean when someone says I oop?
What are the 4 pillars of oop?