I like having all my member variables in my classes/structs to be zero always.
In the past i have used this style in Ansi-C a lot without any problems:
// On the stack
MyStruct valueS = {};
// On the heap or from another memory
MyStruct *valueH = ...
*valueH = {};
Now i am switching to C++ and wanted to do the same kind of trick. And for simple stuff this works, but for some other cases it wont.
For example if i use a class/struct as a member in my struct which have a default constructor, this wont work anymore and i get a compile error like this:
QuoteE1790 the default constructor of "Input" cannot be referenced -- it is a deleted function
Input do not have any constructors at all, but there are a Controller array stored there and the Controller have a Vec2f - which have constructors.
union Vec2f {
struct {
f32 x;
f32 y;
};
struct {
f32 w;
f32 h;
};
f32 elements[2];
inline Vec2f() {
x = y = 0;
}
inline Vec2f(f32 value) {
x = y = value;
}
inline Vec2f(f32 newX, f32 newY) {
x = newX;
y = newY;
}
inline Vec2f(const Vec2f &from) {
x = from.x;
y = from.y;
}
};
struct ButtonState {
b32 isDown;
s32 halfTransitionCount;
inline bool WasPressed() const {
bool result = ((halfTransitionCount > 1) || ((halfTransitionCount == 1) && (isDown)));
return(result);
}
};
struct Controller {
u32 playerIndex;
Vec2f movement;
union {
struct {
ButtonState actionUp;
ButtonState actionDown;
ButtonState actionLeft;
ButtonState actionRight;
};
ButtonState buttons[4];
};
};
struct Input {
f32 deltaTime;
u32 playerOneControllerIndex;
union {
struct {
Controller keyboard;
};
Controller controllers[1];
};
};
void DoStuff() {
Input inputs[2] = { }; // <- Compiler error
Input *currentInput = &inputs[0];
Input *prevInput = &inputs[1];
}
So my question is, how can i do the same trick (Clearing everything) to zero, but makes sure the default constructors for all fields are called?
I know weird question, most people just initialize everything in the constructor... but i hate doing that, unless its meant to be non-zero.
Adding default constructors to all my classes makes the compiler happy, but not me, because nothing gets initialized to zero when i use "something = {};"