I just want to get something straight because while I was learning about inheritance I noticed that I can inherit from an already derived class, and from the most derived class access the Base class's member directly. I think the following shows what I mean:
#include <iostream>
struct Base
{
int member = 0; // All members null
};
struct D1 : Base {};
struct D2 : Base {};
struct D3 : Base {};
struct D4 : Base {};
struct MostDerived : D1, D2, D3, D4 {}; // I know MostDerived now has 4 copies of Base
int main()
{
MostDerived mostderived{};
mostderived.D2::member = 2; // D2::Base::member = 2
mostderived.D3::member = 3; // D3::Base::member = 3
mostderived.D4::member = 4; // D4::Base::member = 4
std::cout << mostderived.D1::member << '\n'; // Haven't touched D1, is still zero
std::cout << mostderived.D1::Base::member << '\n'; // Equals 0, equivalent to above line
std::cout << mostderived.Base::member << '\n'; // Read Base scope directly from most derived, equals zero
mostderived.Base::member++; // Assign to member in Base scope directly from mostderived
// it now equals 1
std::cout << mostderived.D1::member << '\n'; // But also does D1::member equal 1
return 0;
}
So by doing mostderived.Base::member++
I changed the value of mostderived.D1::member
. I'm just wondering if accessing Base
like that makes any sense and why it particularly changed D1
's copy of member. The way I'm picturing the layout is that MostDerived
contains D1
, D2
, D3
, D4
, and each of those contain a Base
, so it looks like the following.