views:

219

answers:

2

Hey,

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.

+2  A: 

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.

PoweRoy
Protected means access from A and subclass of A. And B is a subclass of A.
l245c4l
@l245c4l: B is not a subclass of A because you are using private, not public inheritance. Public inheritance means 'is-a', private inheritance means 'is-implemented-in-terms-of'.
TheJuice
The public/private inheritance is a red-hearing. There is no inter-object access privileges each object only exposes its public interface to other objects (no matter what the class). Friendship is the only way to subvert the access specifiers. Note: class X is a friend of itself.
Martin York
+2  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);
}
UncleBens
So what it means is half of explanations on the Internet are wrong? Because they say that subclass has access to protected members of superclass which is untrue. It has access to them because it HAS them right? So protected means that they can be copied to subclass same as public but cannot be accessed from outside of class. Is that correct?
l245c4l
Your answer is right, but you don't need the apple class at all. (As you say, the compiler complains about the protected access in the Orange class). Just say: An orange cannot change the internals of another fruit - even if it is also an orange.
IanH
UncleBens