Ive got a diamond. I want to access class member. I am using mingw.
Question is: How to access member “top::A” without redeclaring classes
#include <cstdio>
class top {
public:
const char A;
top(): A('t') {}
};
class left: public top {
public:
const char A;
left():A('l'){}
};
class right: public top {};
class bottom: public left, public right {};
int main() {
bottom obj;
printf("%c\n", obj.bottom::right::A); //using right::A, inherited from top::A
printf("%c\n", obj.bottom::left::A); //using left::A and left::top::A is hidden
//printf("%c\n", obj.bottom::left::top::A); //error. How to access it?
return 0;
}
When I remove comment mingw gives me an error:
'top' is an ambiguous base of 'bottom'
Update: Looks like casting types works:
printf("%c\n", static_cast<top>(static_cast<left>(obj)).A);
printf("%c\n", static_cast<left>(obj).::top::A);
printf("%c\n", reinterpret_cast<top&>(obj).A);//considered bad
printf("%c\n", (reinterpret_cast<top*>(&obj))->A);//considered evil
// printf("%c\n", static_cast<top&>(obj).A);//error
Without going for virtual inheritance, you can massage the type a bit to convince the compiler to pick the correct base class: