-
Notifications
You must be signed in to change notification settings - Fork 32
/
Copy pathStatic_Dynamic_Binding.cpp
77 lines (63 loc) · 1.76 KB
/
Static_Dynamic_Binding.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
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
using namespace std;
/*
Dynamic Binding Part I
Static and Dynamic Binding
-Binding : Given an expression, you decide which function will be called.
-STatic Binding : Which function will be called depends on type of pointer
-Dynamic Binding : Which function will be called depends on type of object the pointer points to (virtual functions)
*/
class B {
public:
void f() {
cout << "B::f()" << endl;
}
virtual void g() {
cout << "B::g()" << endl;
}
};
class D: public B {
public:
void f() {
cout << "D::f()" << endl;
}
virtual void g() {
cout << "D::g()" << endl;
}
};
/*
B
^
|
|
|
D
*/
int main() {
B b;
D d;
B *pb = &b;
B *pd = &d; //UPCAST
B &rb = b;
B &rd = d; //UPCAST
//calling functions using object (simple case)
b.f(); //B::f()
b.g(); //B::g()
d.f(); //D::f()
d.g(); //D::g()
//calling functions using pointer
pb->f(); //B::f() //static binding
pb->g(); //B::g() //Dynamic Binding
pd->f(); //B::f() //Static Binding
pd->g(); //D::g() //Dynamic Binding
//Binding of f() is static i.e. which function it calls depends on the type of the pointer
//Something that is statically known by the compiler in the start.
//Binding of g() is dynamic i.e. which function it calls depends on the type of the object it is
//pointing to during runtime. It happens because we have used virtual keyword (g() is a virtual function)
//Same goes like this below
rb.f(); //B::f() //static binding
rb.g(); //B::g() //dynamic binding
rd.f(); //B::f() //static binding
rd.g(); //D::g() //dynamic binding
return 0;
}