I have defined a member var of a derived class to be a reference to a member var of the base class. I am doing this because in the derived class, the name of the reference is more meaningful than the name of the original variable in the base class.
Now I am creating a buffer of char, large enough to contain an object of the derived class. I define a pointer to the derived class, and using a static_cast
, point it to the buffer.
If a member function of the derived class dereferences the base class member var using its original name as defined in the base class, there is no problem.
But if it is dereferenced using the name of the reference, I get a memory access violation.
- Why the different behavior?
How can I achieve what I am trying to do, which is to refer to the variable by a different name in the derived class?
class B { public: int x; B () : x(10) {} }; class D : public B { public: int &y{ x }; // No problem here: inline bool IsXTen () { return ((x == 10) ? true : false); } // Memory Access Violation occurs here: inline bool IsYTen () { return ((y == 10) ? true : false); } }; int main(int argc, char* argv[]) { char buf[sizeof (class D)] = { 0 }; void *pVoid = buf; class D *pd = static_cast<class D*>(pVoid); if (pd->IsXTen ()) { return 1; } if (pd->IsYTen ()) { return 2; } return 0; }