Downcast: why: "A - inaccessible base" B "?

Unlike other examples of this error message, I already have a pointer to Aand you want to get the actual child class.

This type of layout is part of some C code wrapped in C, there Ais some POD structure of C (which does not require dynamic casting), and testthis is some callback in C that calls C ++ functionality and returns the correct cast object should be use. But to prevent the use of C ++ user code for C-Baseclass, I would like to have inheritance protected.

MSVC doesn't complain about this, but g ++ does !? Which one is correct in terms of standards and why?

#include <iostream>

using namespace std;

// plain C structure
struct A{
    int i;
};

// some C++ Wrapper class
struct B: protected A{
  A* get() { return this; }
  void print(){cout << i << endl;}
};



extern "C" {
  // C callback that gives it this pointer
  void test(A* io_self){
     auto b2 = static_cast<B*>(io_self);
     b2->print();
  }
}    

int main()
{
   B b;
   test(b.get());
   return 0;
}

gives:

$g++ -std=c++11 -o main *.cpp
main.cpp: In function β€˜void test(A*)’:
main.cpp:21:43: error: β€˜A’ is an inaccessible base of β€˜B’
          auto b2 = static_cast<B*>(io_self);
                                           ^
+4
2

++ 11 N3337 ( , , ) 5.2.9/11 (static_cast):

" cv1 B", B - , prvalue " cv2 D", D - ( 10) B, " D" " B" (4.10), cv2 - cv-qualification cv-, cv1, B - D, D.

, protected, B A, static_cast (g++ ).

, ++- API- API, , - , C API , ' ++ API

+3

protected, . test, A B . a static_cast , reinterpret_cast reinterpret_cast. B , , B . :

// some C++ Wrapper class
struct B : protected A {
    A* get() { return this; }
    void print() { cout << i << endl; }
    static B* cast_to_b(A* io_self) { return static_cast<B*>(io_self); }
};


extern "C" {
// C callback that gives it this pointer
void test(A* io_self) {
    auto b2 = B::cast_to_b(io_self);
    b2->print();
}
}

, , A* io_self, B, a A undefined.

, protected ? , private , , , B. B a A.

+4

Source: https://habr.com/ru/post/1691123/


All Articles