Sign in to follow this  

C++ default initialization

This topic is 2553 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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;}
};

Share this post


Link to post
Share on other sites
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.)

Share this post


Link to post
Share on other sites

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);}
};


Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

This topic is 2553 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this