Consider this:
class Base {};
class A : public Base {};
class B : public Base {};
class C : public Base {};
class D : public Base {};
class Obj
{
public:
Obj(const Obj&);
private:
A _a;
B _b;
C _c;
D _d;
Base *_current;
};
_current always points to one of _a, _b, _c, or _d. A, B, C, and D can have difference sizes. I want to implement Obj(const Obj&) so that _current of the copy points to the appropriate member in itself.
Is this approach safe:
Obj::Obj(const Obj& obj) :
_a {obj._a},
_b {obj._b},
_c {obj._c},
_d {obj._d}
{
auto objAAddr = reinterpret_cast<const char *>(&obj._a);
auto objCurAddr = reinterpret_cast<const char *>(obj._current);
auto diff = objCurAddr - objAAddr;
auto myAAddr = reinterpret_cast<char *>(&_a);
_current = reinterpret_cast<Base *>(myAAddr + diff);
}
The "base" address could be something else than _a's here, like &_obj (and then apply difference to this).
Is there a better/cleaner alternative?