Search code examples
c++qtqlist

QList pointer function to abstract class


I feel dumb for asking this question because it seems like it would be simple but I don't know how to do it and I can't find it anywhere on the internet. I'm trying to make a function that will return a QList to standard output, the pointer to the abstract class is confusing me. The AbstractStudent class generates an instance of another class Student. here is the function:

QList<AbstractStudent*>* StudentList::returnList() const{


}

Solution

  • A list which stores pointers of an abstract class will be able to store pointers to any sub class of that abstract class.

    Think of the following:

    AbstractStudent.h:

    class AbstractStudent 
    {
        // ...
    };
    

    Student.h:

    class Student : public AbstractStudent
    {
        // ...
    };
    

    Any other class .cpp:

    QList< AbstractStudent* > studentList;
    
    // Each of the following works:
    AbstractStudent* student1 = new Student( /* ... */ );
    studentList.append( student1 );
    
    Student* student2 = new Student( /* ... */ );
    studentList.append( student2 );
    
    Student* student3 = new Student( /* ... */ );
    AbstractStudent* student3_1 = student3;
    studentList.append( student3 );
    

    I am however a bit confused of your last sentence, claiming that AbstractStudent generates Student objects. I would have expected that Student inherits AbstractStudent and some other class generates Student objects, like in my example.