Sizeof (* this) and structure inheritance

Say I have a struct as shown below:

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

And another struct that inherits the parent structure:

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

Assuming sizeof(int) == 4 , is it possible to have a value of 12 passed to getSize() when called from a child structure (currently I get a value of 4)?

I would prefer not to overwrite XYZ() in all substructures as I will have many of them.

+6
source share
5 answers

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 structure what its children have - this is not a very clean solution, but it does the job and avoids the repetition of getSize code.

+3
source

As others say, the this type is the static type of the class in which it is used. However, you can do some pattern tricks:

 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 desired effect.

+7
source

The type of this always a type of static class, so sizeof(*this) always sizeof(ParentStruct) . (Consider: how would sizeof remain a constant expression if the this type was not static?)

If you tell us what you are trying to do, we can offer more convenient alternatives.

+1
source

I believe that sizeof in this case only knows the size of the static *this type (i.e. ParentStruct ), and not its type at runtime ( ChildStruct ). It doesn't matter that XYZ() declared virtual here.

0
source

you get the size of the base structure that you did not overload in the child

-1
source

Source: https://habr.com/ru/post/900169/


All Articles