Reputation: 73
Hi I am trying to do something like the follow.
If have some variables passed from cmd line i.e..
const char * outputtype1
const char * outputtype2
The latter to can be NULL.
I then want to create an instance of a class if outputtype2 is set in command line. How can I have the instance of this class optional. i.e..
if(outputtype2)
{
cats thomas(outputtype2);
}
I then use this later like
thomas.eatfood(whiskers);
This is where it gets upset.Obviously thomas doesnt exist if outputtype2 is null, but why cant I just do this?
if (outputtype2)
{
cats thomas(outputtype2);
}
without error 'thomas' was not declared in this scope. I fear I am missing some fundamental rule here.
Upvotes: 0
Views: 158
Reputation: 113
If I understand your question, the problem is that you create the instance of the class in the if scope. Later you try to call the method eatfood of the object thomas but the object doesn't exist in the current scope.
Maybe you want to do this...
if (outputtype2) {
cats thomas(outputtype1);
thomas.eatfood(whiskers);
}
Or use a pointer...
Cats* thomas = NULL;
if (outputtype2) {
thomas = new Cats(outputtype1);
}
if (thomas != NULL) {
thomas->eatfood(whiskers);
}
Upvotes: 2
Reputation: 180305
You'd probably want boost::optional<cats>
. This allows you to define thomas
up front, and assign cats(outputtype2)
to thomas if and only if it's available.
The consequence is that on any use of thomas
, you will have to check it was actually assigned to.
Upvotes: 5
Reputation: 36441
What you miss is the concept of variable scope and visibility. When you write :
if(outputtype2)
{
cats thomas(outputtype2);
}
that means that the variable thomas
exists only in the block it is declared in. Outside it, thomas doesn't exists anymore, both the object and the reference are destroyed when the control leaves the block. So you cant use them outside!
Find another logic to write your program.
Upvotes: 0