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 is oops with example?
what are the ways in which a constructors can be called?
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?
What is object-oriented programming? Webopedia definition
What is overloading in oops?
What is object and example?
What do you mean by overloading?
What is ambiguity in inheritance?
What is an advantage of polymorphism?
Why is object oriented programming so hard?
What is cohesion in oop?
What do you mean by abstraction?
Can we create object of abstract class?
What is object in oop with example?
Can we define a class within the interface?