Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Friend constructor

Tags:

c++

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.

like image 355
Heretron Avatar asked Jul 12 '13 21:07

Heretron


People also ask

Can constructor be friend?

sure it does. It should work, so there must be a specific syntactic problem in the OP's code, or maybe a misunderstanding regarding how friendliness works.

Is there friend function in C?

Friend class and function in C++ A friend class can access both private and protected members of the class in which it has been declared as friend.

Is there a friend constructor in C++?

Friend function in C++ is used when the class private data needs to be accessed directly without using object of that class. Friend functions are also used to perform operator overloading.

What is a friend class in C?

A friend class in C++ can access the private and protected members of the class in which it is declared as a friend. A significant use of a friend class is for a part of a data structure, represented by a class, to provide access to the main class representing that data structure.


2 Answers

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:
    // ...
like image 70
cdhowie Avatar answered Sep 20 '22 12:09

cdhowie


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);
like image 35
Remy Lebeau Avatar answered Sep 18 '22 12:09

Remy Lebeau