Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public, protected, private

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.

like image 428
l245c4l Avatar asked Apr 29 '26 02:04

l245c4l


2 Answers

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);
}
like image 191
UncleBens Avatar answered Apr 30 '26 16:04

UncleBens


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.

like image 35
RvdK Avatar answered Apr 30 '26 16:04

RvdK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!