Search code examples
c++functionconstructorprivatesmart-pointers

How to access private members of a class from it's private constructor


I have following class and here i'm trying to access private members of the class from private constructor.

class House {
private:
    int len;
    int wid;
    House()
    {
    }
public:
    ~House() 
    {
        std::cout << "destructor call" << std::endl;
    }
    static std::shared_ptr<House> house;
    static auto getHouse(const int length, const int width);

    void setlen(int lenth) { len = lenth; }
    void setwid(int width) { wid = width; }
    int getlen() { return len; }
    int getwid() { return wid; }
};

auto House::getHouse(const int length, const int width)
 {
    House::house = std::make_shared<House>();
    if ((House::house->getlen()==length) && (House::house->getwid()== width)) 
    {
        return House::house;
    }
    else
    {
        House::house->setlen(length);
        House::house->setwid(width);

        return House::house;
    }
}

I get the following error message

Severity Code Description Project File Line Suppression State Error C2248 'House::House': cannot access private member declared in class 'House' TestC++ c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.14.26428\include\memory 1770


Solution

  • Because House does not have a public constructor, code outside the class is not allowed to construct a House. But you're trying to do exactly that, here:

    House::house = std::make_shared<House>();
    

    The implementation of std::make_shared invokes new to construct a new House, but std::make_shared cannot access the private constructor of House. To fix it, you need to construct the House yourself:

    House::house.reset(new House);