title: Can C++ cast the base class back to the derived class?
body: <p>I am trying to create an easy-to-use interface for array indexing in C++. Unfortunately, I just cannot get my code working. And I think the problem is regrading to C++ does not allow me to cast a base class back to the derived class. However, I am not sure why that happens. Please help me with that.</p>
  
  <p>Here is the code.</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  enum index_type {
      single_value,
      sequence,
  };
  
  
  class idx {
  protected:
      index_type t;
  public:
      idx(index_type _t);
      virtual void print_out();
  };
  
  class single_idx:public idx {
  private:
      int sidx;
  public:
      single_idx(int _sidx);
      void print_out();
  };
  
  
  class multiple_idx:public idx {
  private:
      std::vector&lt;int&gt; midx;
  public:
      multiple_idx(std::vector&lt;int&gt; _midx);
      void print_out();
  };
  
  idx::idx(index_type _t):t(_t){
      switch (t) {
          case (single_value):{
          std::cout &lt;&lt; "single_value\n";
          break;
          }
  
          case (sequence):{
          std::cout &lt;&lt; "multiple_value\n";
          break;
          }
      }
  }
  
  single_idx::single_idx(int _sidx):sidx(_sidx), idx(single_value){}
  
  multiple_idx::multiple_idx(std::vector&lt;int&gt; _midx):midx(_midx), idx(sequence){}
  
  void idx::print_out() {
      std::cout &lt;&lt; "lalala\n";
      switch (t) {
          case (single_value):{
          std::cout &lt;&lt; "casting to single\n";
          dynamic_cast&lt;single_idx*&gt;(this)-&gt;print_out();  // ERROR happens here!!!
          break;
          }
  
          case (sequence):{
          std::cout &lt;&lt; "casting to multiple\n";
          dynamic_cast&lt;multiple_idx*&gt;(this)-&gt;print_out();
          break;
          }
      }
  }
  
  void single_idx::print_out() {
      std::cout &lt;&lt; "single value: ";
      std::cout &lt;&lt; sidx &lt;&lt; "\n";
  }
  
  void multiple_idx::print_out() {
      std::cout &lt;&lt; "multiple value: ";
      for (int i : midx) {
          std::cout &lt;&lt; i &lt;&lt; " ";
      }
      std::cout &lt;&lt; "\n";
  }
  
  void f(std::initializer_list&lt;idx&gt; a) {
      for (idx t : a) {
          t.print_out();
      }
  }
  
  int main()
  {
      f({single_idx(1), single_idx(2)});
  }
  </code></pre>