Jump to content
  • Advertisement
Sign in to follow this  
Storyyeller

C++ default initialization

This topic is 2762 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
Advertisement
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
Even if jyk's code works (I think it should), I wouldn't use it: The code is less obvious than the OP's.

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

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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!