I know the definition of private and protected, and what their differences are. However, when I go ahead and play around with them to test every different scenario, I am not getting consistent/expected behavior. This is the paragraph that confuses me (from Teach Yourself C++ in 21 days :) )
In total, three access specifiers exist: public, protected, and private. If a function has an object of your class, it can access all the public member data and functions. The member functions, in turn, can access all private data members and functions of their own class and all protected data members and functions of any class from which they derive.
To be more specific, I wrote a code to see (the code is below the question statement): 1- If Frisky and Boots, two instances of the Cat class, can see each other's private data. By "see"ing, I mean to have member functions that takes the other cat as its argument and be able to set/get its private data. The claim was they should be, and I can confirm it.
2- With the same meaning for "see"ing, can a member function in the cat "Frisky" take as an argument an instance of Mammal, say "Human", and set/get its protected data? I understand from above claim that yes it should, but the code won't compile. It complains that it is protected.
If I am understanding this wrong, what is actually meant by the above paragraph? Any help is appreciated, thanks!
using namespace std;
class Mammal
{
public:
int myNumFeet;
void setMyNumVertebras(int);
protected:
int myNumVertebras;
};
class Cat : public Mammal
{
public:
void tellHisAge(Cat);
void tellHisNumVertebras(Mammal);
void setMyAge(int);
private:
int myAge;
int myWeight;
};
int main()
{
Cat Frisky;
Frisky.setMyAge(3);
Frisky.setMyNumVertebras(23);
Cat Boots;
Boots.setMyAge(4);
Boots.setMyNumVertebras(23);
Mammal Human;
Human.setMyNumVertebras(33);
Frisky.tellHisAge(Boots);
Frisky.tellHisNumVertebras(Human);
return 0;
}
void Cat::tellHisAge(Cat Boots)
{
cout << Boots.myAge <<endl;
}
void Cat::setMyAge(int age)
{
myAge = age;
}
void Mammal::setMyNumVertebras(int num)
{
myNumVertebras = num;
}
void Cat::tellHisNumVertebras(Mammal Human)
{
cout<< myNumVertebras <<endl;
}