title: Access subclass variables from vector of pointers to superclass in C++
body: <p>If I have a vector of pointers to a superclass and add members of a subclass to the vector, I can call a subclass function just fine, but as my code is right now, I can't access variables that are unique to the subclass. How do I access <code>B</code> from a pointer in <code>vec</code>?</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  class Super {
    public:
      int A;
      Super(int a) : A(a) {}
      virtual void foo() = 0;
  };
  
  class Sub : public Super {
    public:
      int B;
      Sub(int a, int b) : Super(a), B(b) {}
      void foo() {
        std::cout &lt;&lt; "calling foo from Sub\n";
      }   
  };
  
  int main() {
    std::vector&lt;Super*&gt; vec;
    vec.push_back(new Sub(2, 3));
    vec[0]-&gt;foo();                                // No problem
    std::cout &lt;&lt; "A: " &lt;&lt; vec[0]-&gt;A &lt;&lt; std::endl; // No problem
    std::cout &lt;&lt; "B: " &lt;&lt; vec[0]-&gt;B &lt;&lt; std::endl; // Compile Error
  }
  </code></pre>