The following code :
#include <iostream>
using namespace std;
class Base {
protected :
int a;
public :
Base() {};
Base(int x) :a(x) {};
};
class Derived : public Base {
public:
Derived(int x) : Base(x) {};
};
int main() {
Derived b(11);
int x;
x=b.a;
}
does not compile because 'int Base::a' is protected within this context.
I know that the Derived class can not access a member of a different Base instance.
I read the following post Accessing protected members in a derived class (and others related posts). So I try different things. For example, I add a new constructor for Derived class.
Derived() {Base(static_cast<Derived*>(this)->a);};
But, as expected, without success.
Is there a mean (some modifers or something else) to access Base
class protected field directly (a
field in Base
must be protected
)?