Take a look at this code:
#include <iostream>
using namespace std;
class A
{
private:
int privatefield;
protected:
int protectedfield;
public:
int publicfield;
};
class B: private A
{
private:
A a;
public:
void test()
{
cout << this->publicfield << this->protectedfield << endl;
}
void test2()
{
cout << a.publicfield << a.protectedfield << endl;
}
};
int main()
{
B b;
b.test();
b.test2();
return 0;
}
B has access to this->protectedfield but hasn't to a.protectedfield. Why? Yet B is subclass of A.
B has access only to the protected fields in itself or other objects of type B (or possibly derived from B, if it sees them as B-s).
B does not have access to the protected fields of any other unrelated objects in the same inheritance tree.
An Apple has no right to access the internals of an Orange, even if they are both Fruits.
class Fruit
{
protected: int sweetness;
};
class Apple: public Fruit
{
public: Apple() { this->sweetness = 100; }
};
class Orange: public Fruit
{
public:
void evil_function(Fruit& f)
{
f.sweetness = -100; //doesn't compile!!
}
};
int main()
{
Apple apple;
Orange orange;
orange.evil_function(apple);
}
this->protectedfield: B enherits of A, this means protectedfield is a property of itself now, so it is able to access it.
a.protectedfield: a is a member of class B, this member has the protectedfield variable which is protected. B cannot touch it, because protected means only access from A within.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With