I'm having trouble with C++ calling elements of an array of type class. Here is a sample of my code;
//village.h
class village
{
public:
class Human
{
public:
void setGender(std::string g);
std::string getGender();
private:
std::string gender;
};
class World
{
public:
void join(Human c, int i);
private:
Human humanArray[20];
};
//village.cpp
void village::World::join(Human c, int i)
{
humanArray[i] = c;
cout << humanArray[i].gender << endl;
cout << c.getGender() << endl;
}
//main.cpp
village::Human h;
village::World world
h.setGender("Male");
world.join(c, 1);
The problem I'm having is, I'm getting error in the line;
cout << humanArray[i].gender << endl;
saying
'gender' is private.
However, didn't I declare the array of type Human? And I'm not getting error when adding so I assume this works ok. But when I try and call an element, I'm getting error. I can't change the variables from private to public.
Change it to
cout << humanArray[i].getGender() << endl;
Technical background on why this works:
The member variable gender
is declared private in the Human
class, thus other classes (and instances of them) cannot access it (without special permission). The member functions Human::getGender()
and Human::setGender()
are declared public, so they can be accessed on instances (objects) of class Human
.
Because a member function can access private members (variables and functions) of the class it belongs to, Human::getGender()
(also true for Human::setGender()
) can access the private gender
member variable of class Human
.
The function join()
is a member of class World
, which is distinct from class Human
, thus it has access to public members only (i.e. has access to Human::getGender()
, but not to Human::gender
)
Accessing the elements of the array has nothing to do with the above. All elements of an array can be accessed by code that has visibility/access to the array (think of the elements as if they were public within the array, with no way to set them private)