Heretron
Heretron

Reputation: 425

C++ Friend constructor

I have two classes : Point, that lives only in Space

class Point
{
private:
    Point(const Space &space, int x=0, int y=0, int z=0);
    int x, y, z;
    const Space & m_space;
};

The constructor is intentionally private, I don't want it to be called directly. I'd like to create Points this way

Space mySpace;
Point myPoint = mySpace.Point(5,7,3);

Is there any way to do so? Thanks.

Upvotes: 16

Views: 22503

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597051

I would do it like this:

class Space
{
public:
    class Point
    {
    private:
        Point(const Space &space, int x=0, int y=0, int z=0);
        int m_x, m_y, m_z;
        const Space & m_space;

    friend class Space;
    };

    Point MakePoint(int x=0, int y=0, int z=0);
};

Space::Point::Point(const Space &space, int x, int y, int z)
    : m_space(space), m_x(x), m_y(y), m_z(z)
{
}

Space::Point Space::MakePoint(int x, int y, int z)
{
    return Point(*this, x, y, z);
}

Space mySpace;
Space::Point myPoint = mySpace.MakePoint(5,7,3);

Upvotes: 7

cdhowie
cdhowie

Reputation: 169143

Yes, declare Space::Point() as a friend method. That method will receive access to Point's private members.

class Point
{
public:
    friend Point Space::Point(int, int, int);
private:
    // ...

Upvotes: 15

Related Questions