General Question About Class Access to Public and Private Variables

I have a general question about accessing public and private variables.

Suppose I have a base class; call it Base.

Suppose I have 2 child classes from Base: Child1 and Child2. Suppose that I have a private variable in Child1; call it privateVariable. (I have an accessor method and a setter method for accessing and setting privateVariable, respectively, inside Child1.) Suppose that I also have a public variable in Child1; call it publicVariable.

Suppose further that I have 2 child classes from Child2: Child2A and Child2B.

Now, I have methods inside Child2A and Child2B that need to operate on privateVariable and publicVariable.

How do I enable Child2A and Child2B to get access to privateVariable and publicVariable? Thanks!
Last edited on
To access private variables you would use functions like so:
1
2
3
4
5
Public:
    void SetPrivateVar(int N){PrivateVar = N;};
    int GetPrivateVar(){return PrivateVar;};
Private:
    int PrivateVar;


To inherit Base functions, you would use Inheritance. Rename Base to human and it makes sense, a Child IS a Human, so it inherits its functions:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Class Human
{
     public:
          void setbirthday();
          void Eat();
};

Class Child1 : Public Human //a child IS a human
{
     //...
};

Class Child2: Public Human
{
    //...
};

Hope this answers your questions.

EDIT: If you would like to have Human access private variables from its child classes then you would put the variables under Protected:.
Last edited on
Thanks. I don't think making privateVariable Protected would do me much good, since Child2 does not inherit from Child1. Also, I don't think making Child1 a friend class of Child2 would be a good idea, because that would defeat the purpose of writing set and get methods in Child1 (i.e., once you make a class a friend of another class, that other class will now have access to friend class's public, protected, and private members by default). So, I need to stick with set and get methods. This is pretty easy to do once I'm in main.cpp -- I simply create an object of type Child1, call its set method to initialize its private variable, and use the element notation to initialize its public variable. However, I'm not so clear on how to do this inside the class definition of Child2A or Child2B (or, perhaps it would be better to do this in Child2, such that I don't have to type the code twice). Any ideas?
Topic archived. No new replies allowed.