class B_mem {
public:
int b_var;
};
class D_mem : public B_mem {
public:
int d_var;
};
class B {
public:
B_mem b_member;
};
class D : public B {
public:
D_mem d_member;
};
int main () {
D derived;
D_mem dmem;
dmem.b_var = 2;
dmem.d_var = 3;
B* b_ptr = &derived;
std::cout << b_ptr->b_member.b_var; // Doesn't print 2
}
How can I structure the classes such that when I set/update D_mem, it automatically sets/updates B_mem (if relevant)? In the example above, I create D and fill D_mem but then access D with a pointer of type B. I want to be able to access the base class members of D_mem in D through B_mem.
I am wondering if there is something with polymorphism, copy constructors, or set functions that will allow me to do this without having to manually keep D_mem and B_mem in agreement.
Of course it doesn't.
The lines
did nothing to change the member variable of
derived
. They are still in an uninitialized state.You can use:
or
Re:
You can do that if you provide member functions that take care of those details and make the member variables private but it gets messy since you have essentially two instances of
B_mem
inD
.The code becomes simpler and easier to maintain if you use a pointer instead of objects.
Here's a sample implementation:
Output: