Reputation: 6008
#include <iostream>
using namespace std;
struct Left
{
char i = 'k';
};
struct Right
{
int a = 99;
};
struct Bottom : Left, Right
{};
int main()
{
Bottom b;
Left* l = &b;
cout << l->i;
Right* r = &b;
cout << r->a;
return 0;
}
// output
// k99
How did this work?
if the memory layout of Bottom is:
Left
Right
Bottom
Then slicing b
(i.e. Bottom
) to Left
object, should be ok, but how can it work when I slice Bottom
to Right
object?
Why isn't static casting required in this case?
Upvotes: 1
Views: 37
Reputation: 182761
Since the compiler knows the types of both pointers, it can apply the necessary offset adjustment. If you print out the values of the pointers, you'll see that they're a bit different.
Upvotes: 2