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 polymorphism used for?
What is the highest level of cohesion?
What is the difference between encapsulation and polymorphism?
What is polymorphism in oops with example?
What is object and example?
What does and I oop mean in text?
design a c++ class for the chess board,provide a c++ class definition for such class(only class definition is required)
What is interface? When and where is it used?
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 meant by multiple inheritance?
What is the main purpose of inheritance law?
Write a program to reverse a string using recursive function?
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).
What is the real life example of polymorphism?
i=20;k=0;
for(j=1;k-i;k+=j<10?4:3)
{
cout<