I want to zero out all members of a derived structure.
There are hundreds of members and more are added every once in a while so I feel that initializing them explic
This assumes that the Base
base class subobject is located at the beginning of Derived
. This won't work if you add another base class.
Further, your code is wrong: pointer arithmetic is performed in terms of objects, not in terms of bytes. You need to use reinterpret_cast<char*>(this)
to perform the arithmetic in terms of bytes. In any case, you still shouldn't do this.
Consider the following, non-ugly, standards-conforming approach utilizing value initialization:
struct Derived : public Base
{
struct DerivedMembers { /* ... */ }
DerivedMembers data;
Derived() : data() { }
};
As long as DerivedMembers
has no constructor, this will value initialize each of the data members of data
, which look like it's exactly the behavior you want.
Or, if you want the members to be accessible without using a "data
" member variable, consider using another base class:
struct DerivedMembers { /* ... */ }
struct Derived : Base, DerivedMembers
{
Derived() : DerivedMembers() { }
};
You should explicitly set all the values to zero and not use memset as this is not portable. The compiler/memory allocation may have housekeeping data stored that you may be overwriting.
You shouldn't do this. You should use initialization lists in each of your classes to avoid the necessity of having to do this. It will be a lot of busy work to get it done on the first pass, but if after that the practice is followed it's trivial.
See this similar question:
The standard does not "frown on the practice"; it gives undefined behavior.
For example:
this + sizeof (Base)
There is nothing in the C++ standard that says that this expression resolves to a pointer to Derived. Indeed, since the type of this
is Derived * const
, then what you've done is pointer arithmetic. C++ will try to add to it as though this
were a pointer to an array of Derived
, the equivalent of this[sizeof(Base)]
. Which probably isn't what you wanted.
Do not walk the dark corridors of undefined behavior if you're not sure how to do it right.
Most importantly of all, even if you pointer gymnastics to actually work, your code becomes very fragile. It may work on this version of your compiler, but it will fail on a later one. Doing something simple like adding a virtual function to Base
will cause chaos in your code, as you will destroy the vtable pointer.
It seems to me that you have a couple of problems:
Base
has nothing virtual in it, why are you publicly deriving from it?