Search code examples
c++oopencapsulation

Accessing private variables through levels of classes.


So in my current understanding of how to use encapsulation correctly it is a good rule of thumb to make variables private and access them through member functions of the class like this:

class Aclass{
private:
    int avar;
public:
    void ch_avar(int val){avar = val};
    int get_avar() {return avar;}
};

My question is how would I access a private member of a class instance which is its self a private member of another class. Here is an example of the way I have been trying to do it (not retyping the example above for brevity)

class LargerClass{
private:
    int other_var;
    Aclass A; //has two instances of class "Aclass" 
    Aclass B; 
public: 
    void ch_other_var(int val){other_var = val;}
    int get_other_var() {return other_var;}

     // this is the important line for the question
    int get_avar(Aclass X){return X.get_avar();} 
}; 

Now In my real program there are a few more levels of this and I keep getting the compilation error that "Aclass" is an unknown type. Even though I have included the header file for Aclass in the Larger class. Since I am stuck I thought It would be good to find out if this is even the correct (or an acceptable way) of doing what I want. I am new to OOP and this feels sloppy to me.


Solution

  • To access the private member of a class instance which is its self a private member of another class, can be done this way. You don't need to pass a Aclass X. It is unneccessary. You can call it by the instance name you have given..

    class LargerClass{
    private:
        int other_var;
        Aclass A; //has two instances of class "Aclass" 
        Aclass B; 
    public: 
        void ch_other_var(int val){other_var = val;}
        int get_other_var() {return other_var;}
    
         // this is the important line for the question
        int get_avar_A(){return A.get_avar();} 
    }; 
    

    If you have 20 instances of Aclass, rather you create a vector of Aclass instances.

    class LargerClass{
    private:
        int other_var;
        Aclass A[20]; 
    public: 
        void ch_other_var(int val){other_var = val;}
        int get_other_var() {return other_var;}
    
         // this is the important line for the question
        int[] get_avar_A()
       {
         int other_var[20];
         for(int i= 0; i<20; i++)
         {
           other_var[i] = A[i].get_avar();
         }
         return other_var;
        } 
    };