I know that protected member of a class can be accessed by subclasses of the previous class.
But I have a problem when I compile this code
Code:
#include <iostream>
using namespace std ;
class A
{
protected :
int _x ;
public :
A( int a ) : _x( a ) { ; }
int x() { return _x ; }
} ;
class B : public A
{
public :
B ( int b ) : A ( b ) { ; }
void add ( A * a ) { if ( a ) a->_x ++ ; }
} ;
int main()
{
A a(1) ;
B b(5) ;
b.add(&a) ;
cout << a.x() << endl;
}
and the compiler message is
Code:
test.cpp: In member function ‘void B::add(A*)’:
test.cpp:8: error: ‘int A::_x’ is protected
test.cpp:20: error: within this context
But if I replace the void add method of class B with
Code:
class B : public A
{
public :
B ( int b ) : A ( b ) { ; }
void add ( A * a ) { if ( a ) static_cast<B *>(a)->_x ++ ; } // this is the line replaced
} ;
the program is compiled and runs well. Apparently the problem is solved but i'm not sure that this casting is 100% secure.
Anyone knows why occurs that and how to solve it, or if that casting is secure.
I use gcc 4.1.2
PD: Sorry about my English, I'm a spanish speaker.