M
Manda Rajo
Guest
The title says the question, thanks. And I explain everything in the comments in the code.
class MyClass
{
friend class MyFriendClass; // This makes the class "MyFriendClass" to
// access all the member variables.
public:
MyClass()
{
m_isValueCalculated = false;
}
int GetValue()
{
if (m_isValueCalculated == false)
{
m_isValueCalculated = true;
m_value = 123;
}
return m_value;
}
private:
bool m_isValueCalculated;
int m_value; // I want that this member variable is only
// accessible by MyClass, and not accessible by MyFriendClass.
};
class MyFriendClass
{
int Get()
{
MyClass c;
int a = c.m_value; // This is not safe, it's possible that the value
// is not calculated yet.
// The question is: How to make the member 'm_value'
// to be not accessible outside of the class "MyClass"?
int b = c.GetValue(); // This is safe
}
};
int main()
{
MyClass c;
int v1 = c.GetValue(); // 123
int v2 = c.GetValue(); // 123
return 0;
}
Continue reading...
class MyClass
{
friend class MyFriendClass; // This makes the class "MyFriendClass" to
// access all the member variables.
public:
MyClass()
{
m_isValueCalculated = false;
}
int GetValue()
{
if (m_isValueCalculated == false)
{
m_isValueCalculated = true;
m_value = 123;
}
return m_value;
}
private:
bool m_isValueCalculated;
int m_value; // I want that this member variable is only
// accessible by MyClass, and not accessible by MyFriendClass.
};
class MyFriendClass
{
int Get()
{
MyClass c;
int a = c.m_value; // This is not safe, it's possible that the value
// is not calculated yet.
// The question is: How to make the member 'm_value'
// to be not accessible outside of the class "MyClass"?
int b = c.GetValue(); // This is safe
}
};
int main()
{
MyClass c;
int v1 = c.GetValue(); // 123
int v2 = c.GetValue(); // 123
return 0;
}
Continue reading...