Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

g++ compilation error "... is protected from within this context" while there's no error with clang

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

like image 556
Timo Avatar asked Jul 13 '15 17:07

Timo


1 Answers

GCC bug. [class.access.base]/p5:

A member m is accessible at the point R when named in class N if

  • m as a member of N is public, or
  • m as a member of N is private, and R occurs in a member or friend of class N, or
  • m as a member of N is protected, and R occurs in a member or friend of class N, or in a member of a class P derived from N, where m as a member of P is public, private, or protected, or
  • there exists a base class B of N that is accessible at R, and m is accessible at R when named in class B.

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.

like image 143
T.C. Avatar answered Nov 13 '22 17:11

T.C.