0

Is it possible to make a vector of a subclass class?

For example, I have the super class University. And I Have the subclasses Student and Major. Major class has a vector of students.

I tried this code but it doesn't work. Any help?

class University {
    public:
        virtual void print(std::ostream& os) = 0;
        virtual ~University() = default;
};


class Student : public University{
        std::string studentName;
    public:
        Student(std::string studentName) : University(), studentName(studentName){}

        void print(std::ostream& os) override {
            os << this->studentName << std::endl;
        }

};

class Major : public University{
    std::vector<Student> students;
    public:
        Major(std::vector<Student> students) : University(), students(students){}
        void print(std::ostream& os) override {
            for(size_t i = 0; i < this->students.size(); ++i){
              os << this->students[i] <<std::endl;
            } 
        }
};

int main(){

    Student student1("Mark");
    Student student2{"Tom"};
    Student student3{"Donald"};
    Student student4{"Duck"};

    std::vector<Student> students {student1, student2, student3, student4};
    
    Major major{students};
    folder.print(std::cout);
}

TheArd
  • 1
  • 2
  • 1
    What does *"it doesn't work."* mean? Do you get compiler errors, runtime errors, wrong results, ...? Please be more precise in your question – UnholySheep Jul 22 '22 at 09:20
  • 1
    Also please provide a proper [mre], this code uses undeclared variables such as `file1` and `folder` - which are either your actual errors, or mistakes you made while creating this question – UnholySheep Jul 22 '22 at 09:22
  • Yes, its perfectly possible, so you are going to have to ask a different question. Like why your code doesn't behave as you want it to. And that means saying how you expect it do behave, and how it actually does behave. – john Jul 22 '22 at 09:23
  • 2
    A student isn't a university. A major isn't a university either. Your modeling doesn't make sense. If it is just for a "print" method, you'd probably be better off with no inheritance and overloading `operator<<` for ostream as is usually done. – Mat Jul 22 '22 at 09:23
  • Note you're violating one of the [SOLID](https://en.wikipedia.org/wiki/SOLID) principles : Single responsibility . A University and a Student should be used for handling data and operations on that data. Pretty printing is a different responsibility and should be handled somewhere else. – Pepijn Kramer Jul 22 '22 at 09:25
  • Looking at your code it seems you are falling into the trap known as *object slicing*. Please see the duplicate for details. – john Jul 22 '22 at 09:29

0 Answers0