* Andy Ward:
Given the following code:
class A
{
protected:
int pro;
};
class B : public A
{
public:
void foo()
{
A * a;
a->pro;
B * b;
b->pro2;
}
protected:
int pro2;
};
The line b->pro2 compiles fine, however the line a->pro does not compile.
Could someone please explain to me why.
A B-object can only access protected A-stuff in the A-part of B-objects.
'protected' isn't a carte blanche to go messing around inside objects.
It only makes the _definitions_ available, "known", to derived classes,
and if you then create an object of such a derived class, say B, you
(the class B code) can access all that you know in your own object.
On the other hand there's no stopping the determined programmer from
doing evil things.
And sometimes that's necessary (e.g. getting access to the container
inside a std::list).
#include <iostream>
class A
{
protected:
int myValue;
public:
A( int aValue ): myValue( aValue ) {}
};
struct Hack: A
{
static int value( A const* p )
{
return static_cast<Hack const*>( p )->myValue;
}
};
class B: public A
{
public:
static int f()
{
A a( 1234 );
// return a.myValue; -- does not compile.
return Hack::value( &a ); // Oooh, dirty!
}
};
int main()
{
std::cout << B::f() << std::endl; // "1234"
}