I would like to implement 'GetParent()' function in here-
class ChildClass;
class ParentClass
{
public:
....
ChildClass childObj;
....
};
class ChildClass
{
friend class ParentClass;
private:
ChildClass();
public:
ParentClass* GetParent();
};
I've tried to create a private member variable which stores pointer to parent object. However this method requires additional memory.
class ChildClass
{
friend class ParentClass;
private:
ChildClass();
ParentClass* m_parent;
public:
ParentClass* GetParent()
{
return m_parent;
}
};
So I used offsetof() macro (performance costs of calling offsetof() can be ignored), but I'm not sure this approach is safe. Would it be work on every situation? Is there any better Idea?
class ChildClass
{
public:
ParentClass* GetParent()
{
return reinterpret_cast<ParentClass*>(
reinterpret_cast<int8_t*>(this) - offsetof(ParentClass, childObj)
);
}
};
See Question&Answers more detail:os