This is a followup related to my previous question where I investigated the problem and found that up- and downcasting seem to be working correctly over public inheritance relations. For example, this code does not even compile:
class A {
};
class B : protected A {
};
int main() {
B b;
static_cast<A*>(&b);
};
G++ gives the following error:
t.cc: In function ‘int main()’:
t.cc:10:21: error: ‘A’ is an inaccessible base of ‘B’
10 | static_cast<A*>(&b);
| ^
However, I think I found the following trick to overcome this limitation. We can cast inside the class, and then export the casting functionality as a public method:
#include <iostream>
class A {
};
class B : protected A {
public:
A* getA() {
return static_cast<A*>(this);
};
static B* fromA(A* a) {
return static_cast<B*>(a);
};
};
int main() {
B b;
// Does not even compile
//std::cout << static_cast<A*>(&b);
// works like charm
std::cout << b.getA() << '\n';
// works also in the reverse direction, although it needs a static method
std::cout << B::fromA(b.getA()) << '\n';
};
I admit it is not very pretty. My tests (in more complex code) show it working, but I am still unsure.
Is it valid C++ code and correct practice?