• C++ Programming for Financial Engineering
    Highly recommended by thousands of MFE students. Covers essential C++ topics with applications to financial engineering. Learn more Join!
    Python for Finance with Intro to Data Science
    Gain practical understanding of Python to read, understand, and write professional Python code for your first day on the job. Learn more Join!
    An Intuition-Based Options Primer for FE
    Ideal for entry level positions interviews and graduate studies, specializing in options trading arbitrage and options valuation models. Learn more Join!

C++: Instantiating Objects Within Switch Loops

Joe Ross

Rutgers MSMF Student
Joined
5/17/11
Messages
59
Points
18
Is it possible to instantiate an object within a switch loop? I keep getting a compile error saying that the initialization is skipped by the remaining cases in the loop.

It works fine instantiating outside of the loop, but, I would like to only have to generate objects if the user chooses to do so, if that is at all possible. Thanks.
 
Joe,
I have never tried it! Maybe switch was not meant for that?? I would consider it a shaky design.

But, maybe it is some kind of object 'factory' you want? Then we could use multiple if { } statements which do work for sure.

Could you post the code?
 
If you instantiate an object outside the switch loop, that object is visible by the code within ALL the case statements of the loop. If you instantiate an object within a switch loop, that object is visible only within the case statement within which it is instantiated. You cannot access that object from any other case statement of the switch loop.
 
If you instantiate an object outside the switch loop, that object is visible by the code within ALL the case statements of the loop. If you instantiate an object within a switch loop, that object is visible only within the case statement within which it is instantiated. You cannot access that object from any other case statement of the switch loop.

That is exactly what I want to have happen, but Visual Studio won't compile it. It looks to me like ALL of the case statements HAVE to be able to access the object based on the error.

Here is the basics of what I am trying to do. This won't compile. It works just fine when I instantiate all objects outside the switch and then call my a.set(), b.set(), c.set() and d.set() functions within the switch. But ideally, if the user only needs an Object A I don't want to instantiate an ObjectB, ObjectC and ObjectD as well.

C++:
case 1:

            cin >> x >> y >> r;

            ObjectA a(x, y, r)

            break;
        case 2:

            cin >> x >> y >> e;

            ObjectB b(x, y, e)

            break;
        case 3:

            cin >> x >> y >> z >> r;

            ObjectC c(x, y, z, r)
            break;
        case 4:
            cin >> x >> y >> z >> e;

            ObjectD d(x, y, z, e)

            break;
 
Put initialization, and then usage of the object, into a block, like:
C++:
case 1:
    cin >> x >> y >> r;
    {
        ObjectA a(x, y, r);
        // do something with a here
    }
    break;
and it will compile then. Then, read about scopes from your C++ book.
 
Put initialization, and then usage of the object, into a block, like:
C++:
case 1:
    cin >> x >> y >> r;
    {
        ObjectA a(x, y, r);
        // do something with a here
    }
    break;
and it will compile then. Then, read about scopes from your C++ book.

thanks! I will try that.
 
Put initialization, and then usage of the object, into a block, like:
C++:
case 1:
    cin >> x >> y >> r;
    {
        ObjectA a(x, y, r);
        // do something with a here
    }
    break;
and it will compile then. Then, read about scopes from your C++ book.

The consequence is that 'a' is created and deleted each time. If this switch was in loop then lots of memory thrashing and performance hit.
 
The consequence is that 'a' is created and deleted each time. If this switch was in loop then lots of memory thrashing and performance hit.

Now that you can see what I am trying to do, what is your recommendation, since the switch IS in a while() loop?
 
Now that you can see what I am trying to do, what is your recommendation, since the switch IS in a while() loop?

First, a code block should have 1 single major responsibility (yours has two). Second, creating object in a loop is wasteful.
So, Create the objects outside the loop like this:

C++:
ExplicitEulerIBVP fdmEE(currentImp, N, J);

CNIBVP fdmCN(currentImp, N, J);

ImplicitEulerIBVP fdmIE(currentImp, N, J);

IBVPFDM* myFDM;

if

(ftype == 1)
{
myFDM = &fdmEE;
 
}
if
(ftype == 2)
{

myFDM = &fdmIE;

}
if
(ftype == 3)
{

myFDM = &fdmCN;

}

NumericMatrix<double, long> myResult = myFDM->result();
 
It's not too clear what you are trying to do but you probably want to read about design patterns. It seems you want to create different objects based on some user input. Check the abstract Factory pattern or the Factory method pattern. They are somewhat similar but have different objectives. This type of problem has been studied and solve elegantly. This switch statement sounds like a disaster in waiting.
 
The consequence is that 'a' is created and deleted each time. If this switch was in loop then lots of memory thrashing and performance hit.

OP complained about the compilation problem, and putting the block around object construction and usage code is a solution; everything further is speculation without looking into the rest of the code. Still, it's pretty much obvious that this piece of code is driven by user input on terminal, so it's certainly going to take *way* longer time for user to type in these values each time (and to corresponding iostream routines to parse corresponding numbers out of them) than for machine to construct/destruct these objects.

Alike - without looking into the rest of the code, one could say the piece of code you provided later is rather inefficient - why would you create three different solver objects if you're going to use only one? This is exactly what OP mentioned above he want to avoid.

As for design patterns: there is a time aspiring C++ programmer should learn about them, and situations when they should be put into use, but in this particular case there is nothing intrinsically wrong with using switch statement and construct objects in the way above, and in any case one should learn the basics first - at this moment, OP would probably benefit more from mentioning that one shouldn't put "using namespace std" in his code, than from all this highly speculative what-if talk.
 
It's not too clear what you are trying to do but you probably want to read about design patterns. It seems you want to create different objects based on some user input. Check the abstract Factory pattern or the Factory method pattern. They are somewhat similar but have different objectives. This type of problem has been studied and solve elegantly. This switch statement sounds like a disaster in waiting.
I agree.
Alain,
Do we tell OP how to solve the problem or do we give advice on using C appropriately? I think we need to at least flag assumptions.

P.S. I have read/written patterns, but avoid mentioning them here.
 
OP complained about the compilation problem, and putting the block around object construction and usage code is a solution; everything further is speculation without looking into the rest of the code. Still, it's pretty much obvious that this piece of code is driven by user input on terminal, so it's certainly going to take *way* longer time for user to type in these values each time (and to corresponding iostream routines to parse corresponding numbers out of them) than for machine to construct/destruct these objects.

Alike - without looking into the rest of the code, one could say the piece of code you provided later is rather inefficient - why would you create three different solver objects if you're going to use only one? This is exactly what OP mentioned above he want to avoid.

As for design patterns: there is a time aspiring C++ programmer should learn about them, and situations when they should be put into use, but in this particular case there is nothing intrinsically wrong with using switch statement and construct objects in the way above, and in any case one should learn the basics first - at this moment, OP would probably benefit more from mentioning that one shouldn't put "using namespace std" in his code, than from all this highly speculative what-if talk.

Depends on whether you consider it to be OK or not. I find it a weak design. We can agree to disagree.
My point was to separate out the creation process from using the object. OP *did* mention that the switch was inside a loop.

And I like asking "why are you using this construction" ? I guessed correctly. Just because you use syntax and get it compiled does not make it good in my book. Organistions have style guides and this syntax may be forbidden.

"using namespace std" is OK when you are learning. Wait till you get to boost, lots of using.
At worst, it will give a compiler error whereas with bespoke code you will get performance hit.
 
Back
Top