title: C++ cast to base class
body: <p>I have a base class <code>A</code> and a derived class <code>B</code>.</p>
  
  <pre><code>class A {
  public:
      int x;
      virtual int getX() {
          return x;
      }
  };
  
  class B : public A {
  public:
      int y;
  };
  </code></pre>
  
  <p>The virtual function is there just to make it polymorphic.
  Next i declare a list of <code>A</code>'s but put <code>B</code>'s inside:</p>
  
  <pre><code>vector&lt;A&gt; list;
  B b1,b2;
  b1.y = 2;
  b2.x = 10;
  
  list.push_back(b1);
  list.push_back(b2);
  </code></pre>
  
  <p>Now i want to go over all elements on the vector and access the <code>y</code> member (which only <code>B</code>'s have):</p>
  
  <pre><code>for (auto it = list.begin(); it != list.end(); ++it) {
      B &amp;cast = dynamic_cast&lt;B&amp;&gt;(*it);
      int value = cast.y;
      std::cout &lt;&lt; value &lt;&lt; std::endl;
  }
  </code></pre>
  
  <p>This code gives a runtime error. Any idea how can i do the cast and access <code>y</code>?</p>