Jump to content
  • Advertisement
Sign in to follow this  
Grahf750

instantiating an object in a case statement?

This topic is 5001 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

I have a menu and I use a switch statement for each option of the menu. in 1 case I create a new Product object called p1, but I get this error: error C2360: initialization of 'p1' is skipped by 'case' label I am used to java where I can create objects in a case is this not allowed in C++ and if it isn't is there a good way to work around it so that if the user does choose that option a product is created?

Share this post


Link to post
Share on other sites
Advertisement
To elaborate, cases are separated by labels, hence the error message; that is to say, they don't produce new scopes. Thus, an object's instantiation could be skipped over by the label, and if subsequent code in that scope needs to use it, you're screwed. It's just an ugly situation as if you did a goto into the middle of a block.

However, the C++ grammar rules allow you to create an 'anonymous' (i.e. not associated with a for or while) scope basically just about anywhere, so in this case you can wrap them around the code for a given case. Then, 'p1' declared in there has the necessary scoping.

By the way, a Java background can be a significant hindrance in C++; a lot of things look similar but behave quite differently, or will mess up in subtle ways (or just use unbelievably large amounts of memory) if you do them in what looks like a natural way. Coder beware.

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!