I have the following code:
#include <iostream>
class BaseClass {
protected:
static int x;
};
int BaseClass::x;
class DerivedA: public BaseClass {
public:
DerivedA() {
x = 3;
}
};
class DerivedB: public BaseClass {
public:
DerivedB() {
std::cout << DerivedA::x;
}
};
int main(int argc, char* argv[]) {
DerivedB b;
}
Compiling with g++ (g++ classtest.cpp) I receive the following error:
classtest.cpp: In constructor ‘DerivedB::DerivedB()’:
classtest.cpp:9:5: error: ‘int BaseClass::x’ is protected
int BaseClass::x;
^ classtest.cpp:25:32: error: within this context
std::cout << DerivedA::x;
When I'm compiling with clang++ (clang++ classtest.cpp) there's no error.
Why is g++ returning the compilation error?
I use g++ version 5.1.0 and clang++ version 3.6.1
GCC bug. [class.access.base]/p5:
A member
mis accessible at the pointRwhen named in classNif
mas a member ofNis public, ormas a member ofNis private, andRoccurs in a member or friend of classN, ormas a member ofNis protected, andRoccurs in a member or friend of classN, or in a member of a classPderived fromN, wheremas a member ofPis public, private, or protected, or- there exists a base class
BofNthat is accessible atR, andmis accessible atRwhen named in classB.
N is DerivedA, m is x, R is the constructor of DerivedB. There exists a base class BaseClass of DerivedA that is accessible at R, and x named in class BaseClass (i.e., BaseClass::x) is plainly accessible at R, so by the fourth bullet point, DerivedA::x is accessible at R.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With