0

I have a QList of type PrintableObject* like:

QList<PrintableObject*> drawables;

This list contains objects of type PrintableX which are subclasses of PrintableObject inserted like:

drawables += &PrintableLine( x, y, x2, y2 );

After this I use the list a loop where I do determine the actual type, make a cast and try to use it:

foreach(PrintableObject* drawable, drawables){

       if(drawable->myClassName == "PrintableLine") {

           PrintableLine* line = (PrintableLine*) drawable;
           painter.drawLine(line->x, line->y, line->x2, line->y2);

       } else if (drawable->myClassName == "PrintableString") {

           PrintableString* string = (PrintableString*) drawable;
           font.setPointSize(string->fontSize);
           painter.setFont(font);

           painter.drawText(string->x, string->y, string->width, string->height, Qt::AlignHCenter | Qt::AlignTop, string->string "if I say?");

       }

   }

Except for, when I try to use my new shiny downcasted object it make a segmentation fault...

Any suggestions?

1 Answers1

3

It seems that you insert a pointer to a dead temporary object into the list:

drawables += &PrintableLine( x, y, x2, y2 );

Try:

drawables += new PrintableLine( x, y, x2, y2 );

You may want also to consider adding a virtual draw method into your PrintableObject class to avoid the need of the RTTI and downcast.

Amir Kirsh
  • 12,564
  • 41
  • 74
  • Thanks guy, you have saved my life! A am not a C++ programmer but got to do it anyway. As for RTTI, I know that is a bad thing, but sometimes we all have to write some smelly code :) – Zhigalin - Reinstate CMs Jun 20 '17 at 10:43
  • 1
    @Zhigalin Happy to save one's life :-) Note: be sure to delete the object that you allocate. – Amir Kirsh Jun 20 '17 at 11:37