forked from ShiqiYu/CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
virtual.cpp
64 lines (55 loc) · 1.12 KB
/
virtual.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#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;
}