Suppose I have a class called Class1. In this class, I have a private variable (call it privateVariable), and I have a public variable (call it publicVariable). Of course, I have a set and get method for setting and returning privateVariable from outside the class (such as in main.cpp).
Suppose I have another class called Class2. Class2 is not related to Class1 in any way (e.g., it is not a child class of Class1, it is not a parent class of Class1, and it is not a composite class of Class1). I have methods in Class2 that need to operate on privateVariable and publicVariable from Class1, which is causing a problem.
Here is my dilemma...
I do not want to make Class2 a child of Class1 (i.e., I cannot solve this problem by making privateVariable protected). Also, if my understanding of friend classes is correct, I cannot also make Class1 a friend of Class2. (If I were to make Class1 a friend of Class2, then this would defeat the purpose of writing a set and get method for privateVariable in Class1, as friend makes all variables available from Class1 to Class2.) I need to do this strictly through the get method in Class1.
In main.cpp, I instantiate an object of Class1 (I provide a value for publicVariable in its constructor), I then instantiate an object of Class2, and then I need to call some methods in Class2 that operate on both privateVariable and publicVariable from Class1. How do I do this? If I were simply trying to set and get these two variables in main directly, then this would be easy. However, since Class2 needs to do this, then I'm at a loss. Thanks!
If class1 has the accessors and mutators you've described, then using main as an example, implement the same for Class2.
What I mean is, what makes it such that the behavior you desire works in main? Answer, because in main you are creating an object of Class1 and then calling the methods of this class on the actual object. What I'm getting to is you need a reference or pointer to an Object of Class1 to interact with in Class2.
example:
1 2 3 4 5 6 7
class Class1; //Forward declaration of class one, notice not #include
class Class2
{
//....
void DoSomethingToClass1(Class1 &); //You pass a reference to an object of type class1 and call getters/setters in this function
};