forked from ShiqiYu/CPP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtti.cpp
40 lines (36 loc) · 1.01 KB
/
rtti.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
#include <iostream>
using namespace std;
class Person
{
protected:
string name;
public:
Person(string name=""):name(name){};
virtual ~Person(){}
string getInfo(){return name;}
};
class Student: public Person
{
string studentid;
public:
Student(string name="", string sid=""):Person(name),studentid(sid){};
string getInfo(){return name+":("+studentid + ")";}
};
int main()
{
Person person("Yu");
Student student("Sam", "20210212");
Person* pp = &student;
Person& rp = student;
Student * ps = (Student*)&person; // danger!
cout << "person.getInfo():" << person.getInfo() << endl;
cout << "pp->getInfo():" << pp->getInfo() << endl;
cout << "rp.getInfo():" <<rp.getInfo() << endl;
cout << "ps->getInfo():" << ps->getInfo() << endl; // danger if getInfo is not virtual
char * p = (char*) 100;
// ps = dynamic_cast<Student*>(&person);
// printf("address = %p\n", ps);
// pp = dynamic_cast<Person*>(&student);
// printf("address = %p\n", pp);
return 0;
}