In a class with no virtual methods or superclass, is it safe to assume (address of first member vari
- by Jeremy Friesner
Hi all,
I made a private API that assumes that the address of the first member-object in the class will be the same as the class's this-pointer... that way the member-object can trivially derive a pointer to the object that it is a member of, without having to store a pointer explicitly.
Given that I am willing to make sure that the container class won't inherit from any superclass, won't have any virtual methods, and that the member-object that does this trick will be the first member object declared, will that assumption hold valid for any C++ compiler, or do I need to use the offsetof() operator (or similar) to guarantee correctness?
To put it another way, the code below does what I expect under g++, but will it work everywhere?
class MyContainer
{
public:
   MyContainer() {}
   ~MyContainer() {}  // non-virtual dtor
private:
   class MyContained
   {
   public:
      MyContained() {}
      ~MyContained() {}
      // Given that the only place Contained objects are declared is m_contained
      // (below), will this work as expected on any C++ compiler?
      MyContainer * GetPointerToMyContainer()
      {
         return reinterpret_cast<MyContainer *>(this);
      }
   };
   MyContained m_contained;  // MUST BE FIRST MEMBER ITEM DECLARED IN MyContainer
   int m_foo;                // other member items may be declared after m_contained
   float m_bar;
};