Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sizeof(*this) and struct inheritance

Say I have a struct like the following:

struct ParentStruct
{
   virtual void XYZ()
   {
      getSize(sizeof(*this));
   }
   int memberX;
}

And another struct which inherits the parent struct:

struct ChildStruct : public ParentStruct
{
    int memberY;
    int memberZ;
}

Assuming sizeof(int) == 4, is it possible to have a value of 12 passed to the function getSize() when called from the child struct (I am currently getting a value of 4)?

I would prefer not to have to overwrite XYZ() in all the sub-structs, as I will have many of them.

like image 291
Tim Cooper Avatar asked Oct 27 '11 00:10

Tim Cooper


2 Answers

As others say, the type of this is the static type of the class its used in. However, you can do some template trickery:

struct Parent{
    virtual void xyz(){ getSize(sizeof(Parent)); }
    int mem1;
};

template<class D>
struct Intermediate : public Parent{
    virtual void xyz(){ getSize(sizeof(D)); }
};

struct Child : public Intermediate<Child>{
    int mem2, mem3;
};

This should give the wanted effect.

like image 124
Xeo Avatar answered Oct 06 '22 21:10

Xeo


You can use templates to get around this problem:

template <typename Child>
struct ParentStruct
{
   virtual void XYZ()
   {
      getSize(sizeof(Child));
   }
   int memberX;
}

struct ChildStruct : public ParentStruct<ChildStruct>
{
    int memberY;
    int memberZ;
}

This way you tell the parent struct who its children are - it's not a super clean solution but it gets the work done and avoids repeating the getSize code.

like image 23
Karel Petranek Avatar answered Oct 06 '22 19:10

Karel Petranek