Results 1 to 2 of 2

Thread: problem in downcasting

  1. #1

    Default problem in downcasting

    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

    Qt Code:
    1. #include <QtCore/QCoreApplication>
    2. #include <QString>
    3. #include <QLinkedList>
    4. #include <iostream>
    5. using namespace std;
    6. class base
    7. {
    8. private :
    9. QString name ;
    10. public :
    11. base(QString name )
    12. {
    13. this->name=name;
    14. }
    15. virtual void foo()
    16. {
    17.  
    18. }
    19.  
    20. };
    21.  
    22. class child: public base
    23. {
    24.  
    25. public :
    26. int num;
    27. child(QString name , int num):base(name)
    28. {
    29. this->num=num;
    30. }
    31.  
    32. virtual void foo()
    33. {
    34.  
    35. }
    36.  
    37. };
    38. int main(int argc, char *argv[])
    39. {
    40. QCoreApplication a(argc, argv);
    41. QLinkedList<base> linkedlist;
    42. child c("1",1);
    43. linkedlist.append(c);
    44. child * p = dynamic_cast<child *>(&linkedlist.first());
    45. if(p != NULL)
    46. {
    47. // why p is always Null ??
    48. std::cout<<dynamic_cast<child &>(linkedlist.first()).num;
    49. }
    50.  
    51. return a.exec();
    52. }
    To copy to clipboard, switch view to plain text mode 

  2. #2
    Join Date
    Nov 2010
    Posts
    4
    Qt products
    Qt3 Qt4 Qt/Embedded PyQt3 PyQt4
    Platforms
    Unix/X11 Windows

    Default Re: problem in downcasting

    Quote Originally Posted by yamen ajjour View Post
    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.

Similar Threads

  1. inheritance and downCasting between objects
    By mickey in forum General Programming
    Replies: 4
    Last Post: 12th November 2007, 19:49

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.