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
Why do we use oop?
what is the 3 types of system development life cycle
What are the components of marker interface?
What is destructor oops?
Why is polymorphism important in oop?
What is the difference between inheritance and polymorphism?
What is constructor overloading in oop?
Where is pseudocode used?
What is abstraction in oop with example?
What is the point of polymorphism?
2. Give the different notations for the class.\
What does and I oop mean in text?
What are the important components of cohesion?
Can enum be null?
Why is it so that we can have virtual constructors but we cannot have virtual destructors?