-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathDynamic Cast 2.cpp
More file actions
52 lines (52 loc) · 1.21 KB
/
Dynamic Cast 2.cpp
File metadata and controls
52 lines (52 loc) · 1.21 KB
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
//dyncast2.cpp
//tests dynamic casts
//RTTI must be enabled in compiler
#include <iostream>
#include <typeinfo> //for dynamic_cast
using namespace std;
////////////////////////////////////////////////////////////////
class Base
{
protected:
int ba;
public:
Base() : ba(0)
{ }
Base(int b) : ba(b)
{ }
virtual void vertFunc() //needed for dynamic_cast
{ }
void show()
{
cout << "Base:ba=" << ba << endl;
}
};
////////////////////////////////////////////////////////////////
class Derv : public Base
{
private:
int da;
public:
Derv(int b, int d) : da(d)
{
ba = b;
}
void show()
{
cout << "Derv:ba=" << ba << ", da=" << da << endl;
}
};
////////////////////////////////////////////////////////////////
int main()
{
Base* pBase = new Base(10); //pointer to Base
Derv* pDerv = new Derv(21, 22); //pointer to Derv
//derived-to-base: upcast -- points to Base subobject of Derv
pBase = dynamic_cast<Base*>(pDerv);
pBase->show(); //"Base: ba=21"
pBase = new Derv(31, 32); //normal
//base-to-derived: downcast -- (pBase must point to a Derv)
pDerv = dynamic_cast<Derv*>(pBase);
pDerv->show(); //"Derv: ba=31, da=32"
return 0;
}