Samuel Burri wrote:
go****@hotmail.com schrieb:
Samuel Burri wrote:
Hi there
I got a simple problem. As you can see in the posted source, I have two
classes, where one is derived from the other. In fact, they also contain
virtual functions. In the function doSomething of Derived I'd like to
access private members of Base from the pointer I receive. The compiler
(gcc 4.0) tells me, that Base::foo is protected and it can't access
although Derived itself has access to the specified element.
Probably its best, if you look at the code below, to understand what I
want to do. My questions are 1. What says the standard? 2. If its not a
bug of the compiler how can I do better?
Any comments are appreciated.
Sam
class Base {
protected:
int foo;
public:
Base() : foo(0) {}
};
class Derived : public Base {
public:
void doSomething( Base* base );
};
void Derived::doSomething( Base* base ) {
base.foo = 10;
}
This should be base->foo = 10; not that it makes any difference, since
the code won't compile even if thus modified.
You're right on that point of course.
What you are doing here is access a member variable inside *another*
object (base) of the type Base; which is an access violation.
Actually the object passed in, isn't of type base, but also of a derived
type.
What you are trying to do (I guess) would be better expressed with
void Derived::doSomething( ) {
this->foo = 10;
}
Well, that does not work, since I need access to both base classes (this
and the one passed by argument) for my function.
Any other hints? Or is there no easy solution I have to redo my whole
design?
From C++/98 Standard
"11.5 Protected member access [class.protected]
1 When a friend or a member function of a derived class references a
protected nonstatic member of a base class, an access check applies in
addition to those described earlier in clause 11.102) Except when
forming a pointer to member (5.3.1), the access must be through a
pointer to, reference to, or object of the derived class itself (or any
class derived from that class) (5.2.5). If the access is to form a
pointer to member, the nestednamespecifier shall name the derived class
(or any class derived from that class)."
I'm not sure, but I think the text:
"Except when forming a pointer to member (5.3.1), the access must be
through a pointer to, reference to, or object of the derived class
itself (or any class derived from that class) (5.2.5)."
says, that the pointer you have must be a pointer to Derived (or any
derived from Derived), and not a pointer to Base.