title: Scope of variables in if statements
body: <p>I have a class that has no default constructor or assignment operator so it is declared and initialized within an if/else statement depending on the result of another function. But then it says that it is out of scope later even though both routes of the conditional will create an instance. </p>
  
  <p>Consider the following example (done with <code>int</code> just to illustrate the point):</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  int main() 
  {
    if(1) {
      int i = 5;
    } else {
      int i = 0;
    }
  
    std::cout &lt;&lt; i &lt;&lt; std::endl;
    return 0;
  }
  </code></pre>
  
  <p>Do variables declared in a conditional go out of scope at the end of the conditional? 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?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>In light of the answers given, the situation is more complex so maybe the approach would have to change. There is an abstract base class A and two classes B and C that derive from A. How would something like this:</p>
  
  <pre><code>if(condition) {
     B obj(args);
  } else {
     C obj(args);
  }
  </code></pre>
  
  <p>change the approach? Since A is abstract, I couldn't just declare <code>A* obj</code> and create the appropriate type with <code>new</code>. </p>