You are here:

C++/Need of private constrctor and destructor?

Advertisement


Question
sir;
pls explain me private constructor and destructor in cpp?

wat is the need of it?

Answer
Hello john, thank you for the question.

There is no concept of making any method or variable private in a cpp file (there is a way to fake it with static). You would make your constructor and destructor private in your class declaration, in the header.

private:

Class() { }

~Class() { }

One reason you would make your Constructor private in your header is so that no other class can create one. One popular example is a singleton. A singleton is a class that can only be instantiated once. Here is an example:

class Singleton
{
private:

static Singleton *instance;

Singleton() { }
~Singleton() { }

public:

Singleton* GetInstance()
{
if(instance == NULL) instance = new Singleton;
return instance;
}

void DeleteInstance()
{
delete instance;
instance = NULL;
}
};
Singleton *Singleton::instance = NULL;

In the above class, the constructor and destructor are private. If you include Singleton.h in another class and try and create an object, it will give a compile error. Therefor the only way to access it is with GetInstance(). This ensures there is one and only one Singleton object. (Note you also need to make the copy constructor and assignment operator private as well, but I left those out for simplicity.)

- Eddie

C++

All Answers


Answers by Expert:


Ask Experts

Volunteer


Eddie

Expertise

I can answer questions about the C++ language, object oriented design and architecture. I am knowledgable in a lot of the math that goes into programming, and am certified by ExpertRating.com. I also know a good deal about graphics via OpenGL, and GUIs.

Experience

I have completed numerous games and demos created with the C++ programming language. Currently employed as a software engineer in the modeling and simulation field. I have about 7 years experience.

©2016 About.com. All rights reserved.