I have come here many times to research issues that others have also had, but have not found a topic directly related to this so figured I'd start my own.
The question I'm having is why are protected attributes in a base class not visible if accessed by dynamic_cast? This seems to be the best way to access attributes if names are shared between multiple base classes (since direct access using this-> would not know which instance is being referred to), however it does not seem to be allowed.
Here is a basic example of what I am referring to:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
|
class Base1
{
public:
Base1(void) : prot(1) {}
protected:
int prot;
};
class Base2
{
public:
Base2(void) : prot(2) {}
protected:
int prot;
};
class Derived : public Base1, public Base2
{
public:
int fprot1(void) {return dynamic_cast<Base1*>(this)->prot;}
int fprot2(void) {return dynamic_cast<Base2*>(this)->prot;}
};
Derived d;
cout << "Base1 prot = " << d.fprot1() << endl;
cout << "Base2 prot = " << d.fprot2() << endl;
|
Attempting to compile gives the following errors:
error C2248: 'main::Base1::prot' : cannot access protected member declared in class 'main::Base1'
error C2248: 'main::Base2::prot' : cannot access protected member declared in class 'main::Base2'
Even though dynamic_cast seems to lose protected access, it is still available as expected if I change class Derived to the following:
1 2 3 4 5 6
|
class Derived : public Base1, public Base2
{
public:
int fprot1(void) {return Base1::prot;}
int fprot2(void) {return Base2::prot;}
};
|
This to me doesn't seem as good though, as it can very quickly get confusing accessing static members or members that may not yet be instantiated (in the case of using the same context to access attributes or methods outside the class scope).
Is there a reason dynamic_cast cuts off protected access? Is this supposed to be the case? If so, is the only workaround what I have posted or are there better solutions?
Thanks in advance for the help!