-
Private Data Access
Say I have a class like this:
Code:
class Space{
public:
Constructor(); // constructor
~Constructor();
private:
Kids*P[3];
}; // end class Space
and another class like this
Code:
class Kids{
public:
Constructor2(); // constructor
~Constructor2();
private:
int friends;
int familyMember;
}
if i had a member function of class Space how could i print what the array of pointers to class Kids points to from that member function in class Space?
-
Have a method in Kids that either returns the data, or prints it:
(the point of private encapsulation is that you cannot (shall not) directly access the data)
Code:
class Space
{
public:
Space();
~Space();
private:
Kids* P[3];
};
class Kids
{
public:
Kids();
~Kids();
int getFriends();
int getFamilyMember();
void printData();
private:
int friends;
int familyMember;
}
Btw, the constructor and the destructor have the same name as the class, not "Constructor".
-
I did what your saying and i sent as one of the parameters to printdata something like this printData(Space A)
and inside print i did this:
A.P[index]->friends but it gives me some type of error like segmentation or something
-
PrintData should print its own values, like this:
Code:
void Kids::PrintData()
{
cout << friends << endl;
cout << familyMember << endl;
}
Then, in the Space class you have a loop tha runs this method for all your kids objects.
Code:
void Space::PrintAllKids()
{
for(int i=0; i<NrOfKids; i++)
{
P[i].PrintData();
}
}