Search code examples
c++c++11pointerslanguage-lawyerprivate-constructor

Pointers to Class Members into a class with a private constructor


Lets say that I have a class with a private constructor and that class will be used to represent a single object. Lets say that I have some non-static members that I want to access without using the scope resolution operator. I've noticed that I can achieve this by creating a pointer to the class type to do so. I was wondering why can I declare pointers to that class even if the default constructor is private? Here is an example program.


// Example program
#include <iostream>
#include <string>


class OnlyOne{
    public:
    void Location(){
        std::cout<<10<<std::endl;
        
    }
    private:
    OnlyOne();
};
int main()
{
    //does not work Location() is not a static member
    //OnlyOne::Location();
     
      // doesn't work because default constructor is private.
     //OnlyOne one;
    //one.Location();
    
    
    OnlyOne* two=nullptr;
    two->Location();
}

I've been looking online to see if I could find an answer and haven't been able to get what I'm looking for.


Solution

  • When you declare a pointer of some type, that type doesn't have to be constructible. In fact, that type doesn't even have to be complete. So, this line:

    OnlyOne* two = nullptr;
    

    is perfectly fine.

    Note that this line:

    two->Location();
    

    invokes undefined behavior, since there is no object pointed at by two, and so there is no object on which you can call the Location member function.

    In fact, since this type is not constructible, two could never point at a valid object. You have to provide a way to construct such an object, either by providing a public constructor, or by having a static member function, that constructs and returns such an object.