1

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{


}
Dmon
  • 220
  • 4
  • 15
  • 2
    So what's the problem/question? Right now you are returning a pointer to a `QList` that holds base class pointers. I can't see why do you need to return a _pointer_ to the `QList`, but it still works. – SingerOfTheFall Sep 20 '13 at 06:48
  • are you tring to print contents of QList to console? – anonymous Sep 20 '13 at 06:57
  • to send the list to standard output so it can be printed in a QTextEdit – Dmon Sep 20 '13 at 06:59

1 Answers1

1

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.

Tim Meyer
  • 12,210
  • 8
  • 64
  • 97
  • AbstractStudent is the base class for the concrete Student class. StudentList is implemented as a list of pointers to AbstractStudent instances - the list will then contain pointers that point to instances of concrete student instances. StudentList is implemented with the Singleton design pattern. (It's like Inception for programming :D). Thanks that helps – Dmon Sep 20 '13 at 07:26
  • Alright. It first sounded like AbstractStudent would have `new Student()` somewhere in its code, so I was confused. ;-) Before you get all too fancy about singletons though, I recommend reading: http://stackoverflow.com/questions/137975/what-is-so-bad-about-singletons and http://misko.hevery.com/2008/08/17/singletons-are-pathological-liars/ – Tim Meyer Sep 20 '13 at 09:23