C++ default initialization

Started by
5 comments, last by fastcall22 13 years, 4 months ago
Is there any way to get numerical types default initialized to 0 in C++ without explicitly initializing them? It seems like there should be a better way to code this.

struct UIQstate{    unsigned int left,right,up,down,jump,shoot;    UIQstate(): left(0), right(0), up(0), down(0), jump(0), shoot(0) {}    unsigned int size() const {return 6;}};
I trust exceptions about as far as I can throw them.
Advertisement
Nope. You could build a type to handle this for you, but that isn't less ugly.
Would this:
UIQstate(): left(), right(), up(), down(), jump(), shoot() {}
Have the desired effect? (IIRC, this will zero-initialize variables of primitive types. However, I may not be remembering correctly.)
Even if jyk's code works (I think it should), I wouldn't use it: The code is less obvious than the OP's.
struct UIQstate{    enum ACTIONS{left,right,up,down,jump,shoot,enum_end};    unsigned int actions[enum_end];    UIQstate(): actions() {}    unsigned int size() const {return static_cast<unsigned>(enum_end);}};
"You insulted me!" I did not say that in the private message Tom Sloper!
One downside of that is that it complicates any code which uses the struct. For example,

++myState.at(UIQstate::DOWN);


Is a little less readable than
++myState.down;
I trust exceptions about as far as I can throw them.
A slightly different variation:

class UIQstate {public:	enum Actions {		left, right, up, down, jump, shoot,		num_actions	};public:	UIQstate() : actions() { // C4351	}public:	unsigned& operator[] ( Actions idx ) {		return actions[ static_cast<int>( idx ) ];	}	const unsigned& operator[] ( Actions idx ) const {		return actions[ static_cast<int>( idx ) ];	}	unsigned numActions() const { 		return num_actions;	}private:	unsigned actions[num_actions];};int main () {	UIQstate t;	t[UIQstate::up] ++;	cout << t[UIQstate::up] << endl;}


Sure it's not as readable as it could be, but it certainly reduces the amount of work it takes when you want to provide UIQstate::operator+(const UIQstate&), UIQstate::operator*, and etc. This is especially useful for a RPG stats structure, for example.

However, if it's readability you're going for, then what you currently have is the best way to go.

This topic is closed to new replies.

Advertisement