DISCLAIMER: This is a cheap and dirty hack, not very C++ish, and haters will hate it. But hey. If you gotta do what you gotta do, and what you gotta do it to is a POD, then this will work.
If you can take the data members that you want to memset
and put them in their own POD, you can memset that POD. To wit (the POD in question here is the BucketOBits
struct):
NOTE: It is important that the datatype you use here is a POD (Plain Old Data). For more about what this means, see this FAQ entry.
#include <cstdlib>
#include <cstring>
class Interface
{
public:
virtual void do_it() const = 0;
virtual ~Interface() {};
};
class Object : public Interface
{
public:
Object();
void do_it() const {};
private:
struct BucketOBits
{
int int_a_;
int int_b_;
int int_c_;
} bucket_;
};
Object::Object()
{
memset(&bucket_, 0, sizeof(bucket_));
};
int main()
{
Interface* ifc = new Object;
}
Even better, you can use the fact that value initialization for integral types means zero-initialization, and get rid of the memset
entirely, while at the same time maybe even making your code a little faster than if you had used memset
. Use default construction for BucketOBits
in the constructor's initialization:
Object::Object() : bucket_()
{
};
EDIT2:
If both base & derived classes have data members that need this zero-init, then you can still use this method by giving each class it's own BucketOBits
. Case in point:
#include <cstdlib>
#include <cstring>
class Interface
{
public:
virtual void do_it() const = 0;
Interface();
virtual ~Interface() {};
private:
struct BucketOBits
{
unsigned base_int_a_;
unsigned base_int_b_;
long base_int_c_;
} bucket_
};
class Object : public Interface
{
public:
Object();
void do_it() const {};
private:
struct BucketOBits
{
int int_a_;
int int_b_;
int int_c_;
} bucket_;
};
Interface::Interface() : bucket_()
{
}
Object::Object() : bucket_()
{
}
int main()
{
Interface* ifc = new Object;
}