Private constructor/destructor

Jun 12, 2009 at 5:16pm
Can constructors and destructors be private?
Jun 12, 2009 at 5:32pm
The constructors can be private (In this way you can hide the copy constructor)
The destructor must be public
Jun 12, 2009 at 5:57pm
Does a class have to have a public constructor? Can it have only private constructors? Does it prevent creation of objects (unless the class has a friend class or a friend function that uses its private constructors) ?
Jun 12, 2009 at 6:47pm
You can make them whatever you want.

A class with only non-public constructors cannot be constructed directly by a user. A class with only non-public destructors cannot be destroyed directly by a user.

There are applications for both. (Singleton, for example).
Jun 15, 2009 at 1:52pm
but below code is not compiling

#include <iostream>

using namespace std;

class ConstructorTest
{
private:
ConstructorTest(){}
};

int main()
{
ConstructorTest t1;
}


Error

cons2.cpp: In function `int main()':
cons2.cpp:8: `ConstructorTest::ConstructorTest()' is private
cons2.cpp:13: within this context

Jun 15, 2009 at 2:11pm

A class with only non-public constructors cannot be constructed directly by a user.


Topic archived. No new replies allowed.