why private constructor prevents object creation C++

4.1k views Asked by At

I have always read that private constructor prevent object creation. I have used them in singleton patterns and I know how to create objects while using private constructor(using static methods etc). I know that constructors are used for initialization of objects.

But I don't understand exactly what makes private constructors prevent object creation. What if my object don't gets initialize. I mean it should throw some garbage but why does it restrict ??

I have checked all the existing answers in stackoverflow but I am not getting the exact concept.

5

There are 5 answers

2
Peter On BEST ANSWER

To create an object in C++, a constructor needs to be called. If the constructor that needs to be invoked is not accessible, then it can't be called, and the object cannot be created.

The point of a private constructor is not preventing object construction. It is about controlling which code can access the constructor, and therefore limiting which code to create an object that is an instance of that class. A private constructor is accessible to all member functions (static or otherwise) of the class, and to all declared friends of the class (which may be individual functions, or other classes) - so any of those can create an instance of the class using a private constructor (assuming the constructor is defined).

If the constructor cannot be invoked, the object cannot be initialised. After all, the job of the constructor is to initialise the object. But if the constructor is inaccessible, then the object cannot be constructed, so it is not possible to have an uninitialised object.

Of course, there is nothing preventing the class from having multiple constructors with different access controls (private, protected, and public). A class with a public constructor can be constructed, using that constructor, by any code. But any attempt to use a private constructor (by a non-member non-friend) will still be rejected. So access control allows the (developer of the) class some measure of control over how an instance is constructed.

Not defining (i.e. not implementing) a constructor does prevent construction of an object. If that constructor is private, the compiler will reject an attempt to call it (unless the function attempting to create an instance is a member or a friend, as above). For members and friends of the class, the compiler will permit access to the constructor, but (in a typical compile-then-link toolchain) the linker will not build an executable, since it cannot resolve a call to a function that is not defined. Using the technique of marking a constructor private and not defining it is a common way of preventing code from constructing an instance of the class (by either preventing the code from compiling, or preventing it from running).

0
StoryTeller - Unslander Monica On

C++ doesn't allow object creation without a call to the constructor. And if the constructor is not accessible, the creation cannot be completed. The lifetime of an object is defined to be between the invocations of the constructor and the destructor.

You can of course allocate raw memory and just cast it to a pointer to object type (as is done in C), but you will not have an object of that class. Until a constructor is called to turn a raw memory region into an object representation, that memory region doesn't formally contain an object.

1
Sam Varshavchik On

Because you can't call a private class method from outside the class, and if the constructor is private, that means you can't create an instance of the class, since creating the object requires the constructor to get called.

A constructor, in this respect, is no different than any other class method. If a class method is private, you already understand that you can't call it from outside the class. And since the constructor must be called to construct an instance of the class, with a private constructor.

0
Sergey Kalinichenko On

It is incorrect to say that marking a constructor private would prevent object creation. All it does is restricting object creation to your code inside the class with only private constructors. You can create a new object, while others can't.

This works well for singletons, because it helps you ensure that your singleton remains the only instance of the class.

0
Raindrop7 On

class private scope doesn't prevent class instantiation but in fact it restrict "who" can create an object.

it is like other member data privately scoped which cannot be accessed from outside but only for accessors and getters and other `friend functions and classes:

#include <iostream>
using namespace std;

class Foo
{
    public:
        Foo(int x) : value(x){ cout << "Foo(int) public ctor" << endl;} // ctor

        void SetValue(int x) {value = x;}  // setter
        int  GetValue()const{return value;}// getter

    private:
        int value;
        Foo(){ cout << "Foo() private ctor" << endl;} // private ctor

        friend ostream& operator<<(ostream& out, Foo& rhs)
        {
            out << rhs.value;
            return out;
        }
        friend Foo* CreateObject();
};

Foo* CreateObject()
{
    Foo* ptrFoo = new Foo;
    return ptrFoo;
}


int main ()
{

    //Foo theFoo;     // error C2248: 'Foo::Foo' : cannot access private member declared in class 'Foo'
    Foo theFoo2(0); // ok
//  cout << theFoo2.value << endl; // error C2248: 'value' : cannot access private member declared in class 'Foo'
    cout << theFoo2.GetValue() << endl; // ok
    cout << theFoo2 << endl;

    Foo* ptrFoo = CreateObject();
    ptrFoo->SetValue(7);
    cout << ptrFoo->GetValue() << endl;


    cout << endl;
    return 0;
}