1

I have two class Window and TitleWindow, which Window is base class. I am doing a downcast with the code:

  Window objs2[num2]; 
     for(int j=0;j<2;j++)
      {
        infile2>>str3>>size2>>str4;
          if(str3=='T')
           {
            TitledWindow *tApp2= (TitledWindow *) &objs2[j];
            tApp2->setT(str4);
            tApp2->resize(size2);
            tApp2->display();
            tApp2->printV(); 
           }
      }

Where setT, resize,display and printV are the member functions of TitleWindow. The code is compiled, but when running it return with memory fault. How should I fix it please?

guangde
  • 63
  • 6
  • 2
    The general advice is to not store polymorphic types in arrays, probably for the same reasons you have problems here. Instead store pointers if you need. – shuttle87 Dec 11 '15 at 03:58
  • 3
    You need to make sure that whatever is pointed to by `&objs2[j]` really is a `TitledWindow ` not just a `Window` as it would seem it is here. The c style cast is dangerous, as it will always work and suppress possible compiler errors or warnings. You should cast using `dynamic_cast`, which should give an error during compilation in this code as the item being cast to is not the true type or sub class. – Paul Rooney Dec 11 '15 at 04:04
  • 1
    I would need to see the code on how you load the array but it looks like [object slicing](http://stackoverflow.com/questions/274626/what-is-object-slicing) is the cause your problem. More than likely `Window objs2[num2];` should be `Window* objs2[num2];` – NathanOliver Dec 11 '15 at 04:10
  • Hi Oliver, Thanks a lot for your reply. I did try to use Window* objs2[num2]; but the same error happen... – guangde Dec 11 '15 at 04:27
  • Can you explain what you are trying to do a bit better? What are you expecting `objs2` to hold? Will there be other types of `Windows` in that same array? – Paul Rooney Dec 11 '15 at 05:50
  • what object pointers do you store in objs2 array? and you should use dynamic_cast to do do the cast and check its result . – hiitiger Dec 11 '15 at 09:27
  • Thanks everyone for your help. I found the bug. It is the downcast causing problem. – guangde Dec 14 '15 at 02:07

0 Answers0