I\'m trying to access the member variable x in struct Top using a Bottom object.
The code is the following:
#include
The problem is that C++ has no way to directly express the concept of "multiple-level" class members, such as "the member x
of the Top
subobject of Left
". What Left::Top::x
means is "the member x
in the type denoted by Left::Top
" - and the type denoted by Left::Top
is exactly Top
.
This is why you can write odd things like
int Left::* ptr = &Right::Top::x;
because the right hand side of the =
is exactly equivalent to &Top::x
, and a pointer-to-base-class-member is implicitly convertible to a pointer-to-derived-class-member. (The result of this conversion still refers to the member in the base-class subobject of the derived class.)
To disambiguate, you can either do something along the lines of static_cast
or use a pointer-to-member - given int Left::* ptr = &Top::x;
, b.*ptr
will refer to the x
in the Top
subobject of the Left
subobject of b
.