I would like to access Base
class members in an unqualified way (why? macro sorcery) from outside of the class itself. The strategy is do it in Derived
class and cast the pointer-to-Base
to pointer-to-Derived
(even though the instance is not a Derived
).
The code compiles and runs correctly as far as I tried: is this by standard or by accident (and UB by standard)? coliru link
#include<iostream>
struct Base{
int a=3;
};
struct Derived: public Base{
int getA(){
// this scope has unqualified access to Base class members
return a;
}
};
int main(void){
Base b;
std::cerr<<((Derived*)(&b))->getA()<<std::endl;
}
The cast (Derived*)(&b)
will be equivalent to static_cast<Derived*>(&b)
which has undefined behavior if the object that &b
points to is not actually a subobject of a Derived
object. See [static.cast]/11 of the current C++ standard draft (equivalent language exists at least since C++11).
Your program therefore has undefined behavior, since there isn't any Derived
object created at all and b
is not a subobject of a Derived
object.
Note that the cppreference page on static_cast
is not explicit in stating that the cast itself has undefined behavior, but it has, as quoted above.