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
and the compiler message isCode:#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; }
But if I replace the void add method of class B withCode: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
the program is compiled and runs well. Apparently the problem is solved but i'm not sure that this casting is 100% secure.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 } ;
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.



LinkBack URL
About LinkBacks



) there might be problems with the broader design itself.