-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathoverriding_example.cpp
More file actions
46 lines (36 loc) · 893 Bytes
/
overriding_example.cpp
File metadata and controls
46 lines (36 loc) · 893 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
#include <iostream>
using namespace std;
struct B {
virtual void f() const { cout << "B::f()" << endl; }
void g() const { cout << "B::g()" << endl; } // not virtual
};
struct D : B {
void f() const { cout << "D::f()" << endl; } // overrides B::f()
void g() { cout << "D::g()" << endl; }
};
struct DD : D {
void f() { cout << "DD::f()" << endl; } // doesn't override D::f() (not const)
void g() const { cout << "DD:g()" << endl; } // hides B::g()
};
// a D is a kind of B, so call() can accept a D
// a DD is a kind of D and a D is a kind of B, so call() can accept a DD
void call(const B& b) {
b.f();
b.g();
}
// a purely technical example that illustrates overriding
int main() {
B b;
D d;
DD dd;
call(b);
call(d);
call(dd);
b.f();
b.g();
d.f();
d.g();
dd.f();
dd.g();
return 0;
}