Overriding virtual function not working, header files and c++ files

c++, inheritance, overriding, virtual

Solution

EDIT: after your edit the problem is clear.

The problem is that you are storing base concrete objects in a STL container. This creates a problem called object slicing.

When you add a student to a `vector<Student>`, since the allocator of the vector is built on the `Student` class, every additional information on derived classes is just discarded. Once you insert the elements in the vector they become of base type.

To solve your problem you should use a `vector<Student*>` and store directly references to students in it. So the allocator is just related to the pointer and doesn't slice your objects.

vector<Student*> uniStudent;
...
uniStudent.push_back(s);
uniStudent[0]->study();

Mind that you may want to use a smart pointer to manage everything in a more robust way.

Problem

We have a parent class called Student. We have a child class: StudentCS. Student.h: ``` #include <iostream.h> #include<string.h> #include<vector.h> #include "Course.h" class Course; class Student { public: Student(); Student(int id, std::string dep, std::string image,int elective); virtual ~Student(); virtual void Study(Course &c) const; // this is the function we have a problem with void setFailed(bool f); [...] }; ``` Student.cpp: ``` #include "Student.h" [...] void Student::Study(Course &c) const { } ``` And we have StudentCS.h: ``` #include "Student.h" class StudentCS : public Student { public: StudentCS(); virtual ~StudentCS(); StudentCS (int id, std::string dep, std::string image,int elective); void Study(Course &c) const; void Print(); }; ``` And StudentCS.cpp: ``` void StudentCS:: Study (Course &c) const{ //25% to not handle the pressure! int r = rand()% 100 + 1; cout << r << endl; if (r<25) { cout << student_id << " quits course " << c.getName() << endl; } } ``` We create student in the main: ``` Student *s; vector <Student> uniStudent; [...] if(dep == "CS") s = new StudentCS(student_id,dep,img,elective_cs); else s = new StudentPG(student_id,dep,img,elective_pg); uniStudent.push_back(*s); ``` Then we call to study, but we get the parent study, and not the child! Please help! The code compiles but when run and called on the uniStudent.Study() it uses the parent and not the child

Original source