-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path50ptrtoderivedcl.cpp
More file actions
63 lines (54 loc) · 2 KB
/
Copy path50ptrtoderivedcl.cpp
File metadata and controls
63 lines (54 loc) · 2 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
53
54
55
56
57
58
59
60
61
62
63
#include <iostream>
using namespace std;
class BaseClass
{
public:
int var_base;
void display()
{
cout << "Base class variable var_base value is " << var_base << endl;
}
};
class DerivedClass : public BaseClass
{
public:
int var_derived;
void display()
{
cout << "Base class variable var_base value is " << var_base << endl;
cout << "Derived class variable var_derived value is " << var_derived << endl;
}
};
int main()
{
// Base class pointer can point to the derived class object
BaseClass *base_class_pointer; // this is a base class pointer
BaseClass obj_base;
DerivedClass obj_derived; // this is a derived class object
base_class_pointer = &obj_derived; // this will not throw any error as it is very legal to do
DerivedClass *derived_class_pointer; // This is not legal or valid to do
// derived_class_pointer = &obj_base; // derived class pointer cannot point to a base class object
base_class_pointer->var_base = 12;
base_class_pointer->display();
/*
SINCE THE POINTER IS OF BASE CLASS, IT WILL ONLY LET THE DERIVED OBJECT TO ACCESS BASE CLASS INHERITED MEMBERS
THE POINTER CANNOT ACCESS THE DERIVED CLASS MEMBERS
IT CAN ONLY ACCESS THE INHERITED BASE CLASS MEMBERS
THE DERIVED OBJECT ONLY STORES THAT VALUE AND NOT GOVERN THE POINTER
base_class_pointer->var_derived = 8; won't work and will give error
It will only access the class function it belongs to in case of overloading
This is called late binding
*/
derived_class_pointer = &obj_derived;
derived_class_pointer->var_base = 78;
derived_class_pointer->var_derived = 783;
derived_class_pointer->display();
// This derived class pointer now points to the derived class display function
return 0;
}
/*
SO FROM THIS WE CAN SAY THAT
IN RUN TIME POLYMORPHISM,
The compiler checks the pointer and the class it is of to finally select the members to access with the pointer
this is done in run time
*/