PDA

View Full Version : problem in downcasting



yamen ajjour
18th November 2010, 23:13
i've wrote this program and i was trying to make a downcast but it seems the something went wrong !
and by the way can i get rid of foo function ?? it seems that g++ doesn't consider the class base polymorphic if i don't provide a virtual function although i don't need it ! i just want to access the field Num in the way described below
thank you :)



#include <QtCore/QCoreApplication>
#include <QString>
#include <QLinkedList>
#include <iostream>
using namespace std;
class base
{
private :
QString name ;
public :
base(QString name )
{
this->name=name;
}
virtual void foo()
{

}

};

class child: public base
{

public :
int num;
child(QString name , int num):base(name)
{
this->num=num;
}

virtual void foo()
{

}

};
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
QLinkedList<base> linkedlist;
child c("1",1);
linkedlist.append(c);
child * p = dynamic_cast<child *>(&linkedlist.first());
if(p != NULL)
{
// why p is always Null ??
std::cout<<dynamic_cast<child &>(linkedlist.first()).num;
}

return a.exec();
}

nguarracino
19th November 2010, 03:15
i've wrote this program and i was trying to make a downcast but it seems the something went wrong !
and by the way can i get rid of foo function ?? it seems that g++ doesn't consider the class base polymorphic if i don't provide a virtual function although i don't need it ! i just want to access the field Num in the way described below
thank you :)


You need to have a QLinkedList<base*>. If it's not a list of pointers or references, when you append a child to the list, it will be sliced to a base.