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
m
is accessible at the pointR
when named in classN
if
m
as a member ofN
is public, orm
as a member ofN
is private, andR
occurs in a member or friend of classN
, orm
as a member ofN
is protected, andR
occurs in a member or friend of classN
, or in a member of a classP
derived fromN
, wherem
as a member ofP
is public, private, or protected, or- there exists a base class
B
ofN
that is accessible atR
, andm
is accessible atR
when 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