-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcasting.cpp
More file actions
47 lines (38 loc) · 953 Bytes
/
Copy pathcasting.cpp
File metadata and controls
47 lines (38 loc) · 953 Bytes
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
#include<iostream>
class Base {
public:
Base() {}
virtual ~Base() {}
};
class Derived : public Base {
public:
Derived(){}
~Derived(){}
};
class Another: public Base {
public:
Another(){}
~Another(){}
};
int main() {
// static type casting
int a = 5;
/*
double value = (int)5;
*/
double value = static_cast<int>(5);
double s = value + a;
// reinteprest cast
// This adds compile time checking, as compared to c style cast
// Here we are typing to read the memory address of s as Another class pointer
Another* s1 = reinterpret_cast<Another*>(&s);
// use of dynamic cast
Derived* derived = new Derived();
Base* base = derived;
Another* ac = dynamic_cast<Another*>(base);
// Derived* ac = dynamic_cast<Derived*>(base);
if (!ac) {
std::cout << "Base variable cannot be typecasted to Another" << std::endl;
}
// if we want to check
}