Protected member inaccessible from derived class - why

A

avasilev

Hi all,
Quick question: why doesn't this code compile:

class Base
{
protected:
int a;
};

class Derived: public Base
{
public:
void test(Base* b)
{
b->a = 5;
}
};

int main()
{
Derived d;
Derived d1;
d.test(&d1);
}
The error is that Base::a is protected in the test() method of Derived
Thanks in advance
Best regards
Alex
 
V

Victor Bazarov

Quick question: why doesn't this code compile:

class Base
{
protected:
int a;
};

class Derived: public Base
{
public:
void test(Base* b)
{
b->a = 5;
}
};

int main()
{
Derived d;
Derived d1;
d.test(&d1);
}
The error is that Base::a is protected in the test() method of Derived

The access to protected members is allowed only for the '*this' object,
and not for any other object. IOW, in 'Derived::test' you should be
able to access 'this->a', but not 'anyotherBase.a'. That's just the
rule of the language.

V
 
A

avasilev

The access to protected members is allowed only for the '*this' object,
and not for any other object.  IOW, in 'Derived::test' you should be
able to access 'this->a', but not 'anyotherBase.a'.  That's just the
rule of the language.

V

Thanks for the response, Victor

I thought about this, but I think I remember having written operator
methods, that contain something like:


MyClass& operator=(MyClass& other)
{
mMember = other.mMember;
...
}

where mMember was internal protected stuff. IS there any exception
for operators, or I am just mistaken?

Thanks
 
A

Alf P. Steinbach

MyClass& operator=(MyClass& other)
{
mMember = other.mMember;
...
}

where mMember was internal protected stuff. IS there any exception
for operators, or I am just mistaken?

Can you see any obvious difference above?

Cheers & hth.,

- Alf
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,754
Messages
2,569,521
Members
44,995
Latest member
PinupduzSap

Latest Threads

Top