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.
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.
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.
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.
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.
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:
// ...
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With