-
Notifications
You must be signed in to change notification settings - Fork 7
/
methodOverridingAndHiding.cpp
59 lines (52 loc) · 1.81 KB
/
methodOverridingAndHiding.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
#include<bits/stdc++.h>
using namespace std;
class A {
public:
void print() {
cout << "In print function of class A\n";
}
void showData() {
cout << "In showData function of class A\n";
}
};
class B: public A {
public:
void print() { // method overriding
cout << "In print function of class B\n";
}
void showData(int x) { // method hiding
cout << "In showData function of class B\n";
}
};
int main() {
/*
Method overriding:
--> When you want the same functionalities in your child class but with different functionalities
--> The entire function prototype should be same both in child and parent (No difference allowed)
Method hiding:
--> A function with same name but different arguments in parent and child class
*/
B b;
/*
What happens when you do b.print()?
--> When this line is written, during compilation it is the duty of the compiler to bind the call
to the declaration (Early binding)
--> So the compiler searches through the member functions of the caller object and checks for
functions named print().
--> If it finds a function in class B, it stops the search process and binds the call to that function
--> If it does not find, the compiler continues to search it in the parent class and so on
*/
b.print();
b.A::print();
/*
Why does the line below cause a CE?
--> During compilation, the compiler starts the process of searching and binding from the
caller class (B)
--> So in this class it has a function with the name showData but with different arguments.
--> If the name matches, the compiler stops searching and that point and the CE is caused
due to mismatch of arguments.
*/
// b.showData(); Gives CE
b.showData(1);
b.A::showData();
}