Possible Duplicate:
Accessing protected members in a derived class
If I have an abstract base class and a concrete templated class that derives from it, which has a method that uses a pointer to the base class – it seems that the derived class stops seeing itself as derived from it:
class AbstractBase
{
protected:
virtual void test() = 0;
};
template < class T >
class Derived : public AbstractBase
{
public:
virtual void call( AbstractBase* d ) { d->test(); } // Error!
protected:
virtual void test() {}
};
int main()
{
Derived< int > a;
Derived< int > b;
b.call( &a );
return EXIT_SUCCESS;
}
This errors with:
‘virtual void AbstractBase::test()’ is protected
The compiler’s not wrong, it’s definitely protected – but if Derived< T > inherits from AbstractBase, why is it complaining?
The reason it isn’t allowed is because
AbstractBaseas a type declarestestto be protected. This makes it private to all unless the current class is a direct descendant ofAbstractBase. Even so, that class can only access the member though an object of the same class, not a different descendant, and not directly fromAbstractBaseitself.You can, as demonstrated above, just allow it for pointers of the same type. Alternatively, you can create a proxy base class for
Derivedto implement yourvirtualmethod to calltest. This will allow access from differentDerivedtypes.And can be accessed this way: