Is there a way to declare member4 that only visible to Function1 and it is not shared by all instances?
class Test
{
public:
void Function1()
{
???? int member4 //visble to Function1 (single instance)
}
void Function2()
{
static int member3;// visble to Function2 (all instances)
}
private:
int member1; // visble to Function1 and Function2 (single instance)
static int member2;//visble to Function1 and Function2 (all instances)
};
CodePudding user response:
Your question looks like an XY Problem. Anyway, here are two possible solutions.
First, you could wrap the field into a class and declare the method as a friend:
class Test {
public:
// Don't forget to init Data:
Test();
void function1();
void function2();
private:
class Data;
Data *data;
};
class Test::Data {
int get() { return 42; }
friend void Test::function1();
};
void Test::function1() {
int secretData = data->get();
}
void Test::function2() {
// Will not compile:
// int secretData = data->get();
}
This solution smells. Much better would be to extract the entity that has this secret member into a separate class:
class AnotherEntity {
public:
void function1() {
// use secretData here;
}
private:
int secretData;
};
class Test : public AnotherEntity {
public:
void function2();
private:
};