class Person
{
public:
Person(std::string& name,long id) : name_(name), id_(id) {}
~Person() {}
private:
std::string& name_;
long id_;
};
class Student : public Person
{
public:
Student(std::string& name, long id) : Person(name,id) {}
Student(std::string& name, long id, const std::vector<int*>& courses) : Person(name,id), courses_(courses) {}
virtual ~Student() {
std::vector<int*>::iterator it;
for (it = courses_.begin(); it != courses_.end(); ++it)
delete (*it);
}
const std::vector<int*>& getCourses() const { return courses_; }
private:
std::vector<int*> courses_;
};
int main(){
std::string name("Rina");
std::vector<int*> courses;
courses.push_back(new int(1345));
Person* p = new Student(name,37,courses);
Student* s = (Student*)p;
std::cout << (*(s->getCourses().at(0)));
delete p;
}
I understand that the
delete p;
makes us realize the problem that
~Person()
is not virtual.
My question is: why should
~Person()
be virtual?
For the same reason that you make other methods virtual.
wouldn’t handle subclasses of
Personproperly if the destructor wasn’t virtual. i.e. it would simply invoke thePersoncomponent and not the subclass component (e.g.Employee)