In C, in order to assure that all structs are zeroed I wrap malloc
with:
void* safe_malloc(size_t size){
void *result = malloc(size);
memset(result, 0, size); //NULL check ommitted for brevity
return result;
}
so that I can avoid doing:
struct Foo {
int bar;
int bat;
};
struct Foo *tmp = malloc(sizeof(struct Foo));
tmp->bar = 0;
tmp->bat = 0; // I want to avoid this laundry list of initializers
I want to do something similar for C++ whereby I want all members of a class to be initialized to zero like what is done automatically in Java. There are two problems that come to mind using a solution like the C solution: 1. you cant clear the vtable ptr and 2. a subclass will clear inherited member values.
class Foo {
public:
int bar;
int bat;
Foo(int bar){
this->bar = bar;
this->bat = 0; // I dont want to explicitly have to initialize this here
}
}
class Baz : public Foo {
public:
int bam;
Baz(int bar, int bam) : Foo(bar) {
this->bam = bam;
}
}
How can I avoid the laundry list equivalent in C++?