-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path51virtualfunc.cpp
More file actions
40 lines (36 loc) · 1.1 KB
/
Copy path51virtualfunc.cpp
File metadata and controls
40 lines (36 loc) · 1.1 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
#include <iostream>
using namespace std;
class BaseClass
{
public:
int var_base = 9;
virtual void display() // the virtual here told the compiler to seek the other display of the object's class and not of the pointer
{
cout << "Base class variable var_base value is " << var_base << endl;
}
};
class DerivedClass : public BaseClass
{
public:
int var_derived = 10;
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()
{
BaseClass *base_class_pointer;
BaseClass obj_base;
DerivedClass obj_derived;
base_class_pointer = &obj_derived;
/*
for the base class pointer pointing to derived class object to access the derived class function of the same name,
use virtual before the base class function
this creates a virtual function
it tells the compiler that there is another function with the same name in the object's class so use that instead
*/
base_class_pointer->display();
return 0;
}