Scope of variables in if statements
"Do variables declared in a conditional go out of scope at the end of the conditional?"
Yes - the scope of a local variable only falls within enclosing brackets:
{
int x; //scope begins
//...
}//scope ends
//x is not available here
In your case, say you have class A
.
If you're not dealing with pointers:
A a( condition ? 1 : 2 );
or if you're using a different constructor prototype:
A a = condition ? A(1) : A(2,3);
If you're creating the instance on the heap:
A* instance = NULL;
if ( condition )
{
instance = new A(1);
}
else
{
instance = new A(2);
}
or you could use the ternary operator:
//if condition is true, call A(1), otherwise A(2)
A* instance = new A( condition ? 1 : 2 );
EDIT:
Yes you could:
A* x = NULL; //pointer to abstract class - it works
if ( condition )
x = new B();
else
x = new C();
EDIT:
It seems what you're looking for is the factory pattern (look it up):
class A; //abstract
class B : public A;
class C : public A;
class AFactory
{
public:
A* create(int x)
{
if ( x == 0 )
return new B;
if ( x == 1 )
return new C;
return NULL;
}
};
Do variables declared in a conditional go out of scope at the end of the conditional?
Yes.
What is the correct way to handle the situation where there is no default constructor but the arguments for the constructor depend on certain conditionals?
Write a function that returns a value, from which you copy.
T foo()
{
if(condition)
return T(x);
return T(y);
}
void bar()
{
T i(foo());
}
Edit:
Since A is abstract, I couldn't just declare A* obj and create the appropriate type with new.
What do you mean? That's exactly how dynamic typing works. Except I wouldn't use a raw pointer, I would use a unique_ptr.
std::unique_ptr<A> obj;
if(condition) {
obj = std::unique_ptr<A>(new B(args));
} else {
obj = std::unique_ptr<A>(new C(args));
}