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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With