Sign in to follow this  

instantiating an object in a case statement?

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

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