Let’s look at the example first, what will be the output?
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string name;
Person(string n) : name(n) {}
virtual void print()
{
cout << "Name: " << name << endl;
}
};
class Person2
{
public:
string name;
Person2(string n) : name(n) {}
virtual void print() = 0;
};
class Student : public Person
{
public:
string id;
Student(string n, string i) : Person(n), id(i) {}
void print()
{
cout << "Name: " << name;
cout << ". ID: " << id << endl;
}
};
void printObjectInfo(Person &p)
{
p.print();
}
int main()
{
{
Student stu("yu", "2019");
printObjectInfo(stu);
}
{
Person *p = new Student("xue", "2020");
p->print(); // if print() is not a virtual function, different output
delete p; // if its destructor is not virtual
}
// { //if you want to call a function in the base class
// Student stu("li", "2021");
// stu.Person::print();
// Person * p = new Student("xue", "2020");
// p->Person::print();
// delete p;
// }
return 0;
}
- But if we define
print()
function as a virtual function, the output will be different. - Static binding: the compiler decides which function to call
- Dynamic binding: the called function is decided at runtime.
- Keyword virtual makes the function virtual for the base and all derived classes.
Virtual Destructors
If a virtual destructor is not virtual, only the destructor of the base class is executed in the follow examples.
析构函数一定是虚函数
Person * p = new Student("xue", "2020");
p->print();
...
...
delete p; //if its destructor is not virtual