Skip to content

Commit 3bc3f01

Browse files
committed
override
1 parent 2b71e18 commit 3bc3f01

3 files changed

Lines changed: 54 additions & 2 deletions

File tree

‎cpp/README.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@
4545
1. [Static constructor for private members](static_constructor_private.cpp)
4646
1. [POD](pod.cpp)
4747
1. Inheritance
48+
1. [`override` identifier](override.cpp)
4849
1. [Inheritance override](inheritance_override.cpp)
4950
1. [Inherit overload_hide](inherit_overload_hide.cpp)
5051
1. [Inheriting constructor](inheriting_constructor.cpp)

‎cpp/inheritance_override.cpp‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// Let's learn how method name resolution works with inheritance.
2+
13
#include "common.hpp"
24

35
class B {
@@ -44,17 +46,21 @@ int main() {
4446
assert(c.B::i == 1);
4547
assert(cp->B::i == 1);
4648

49+
#if 0
4750
// ERROR: ambiguous because on multiple base classes.
48-
//c.iAmbiguous = 0;
51+
c.iAmbiguous = 0;
52+
#endif
4953
c.B::iAmbiguous = 0;
5054

5155
// Analogous for methods.
5256
callStack.clear();
5357
assert(c.f() == 2);
5458
assert(c.B::f() == 0);
5559

60+
#if 0
5661
// ERROR ambiguous.
57-
//c.fAmbiguous();
62+
c.fAmbiguous();
63+
#endif
5864
assert(c.B::fAmbiguous() == 0);
5965
assert(c.B2::fAmbiguous() == 1);
6066
}

‎cpp/override.cpp‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
// https://stackoverflow.com/questions/13880205/is-the-override-keyword-just-a-check-for-a-overridden-virtual-method/54535784#54535784
2+
// https://stackoverflow.com/questions/29145476/requiring-virtual-function-overrides-to-use-override-keyword
3+
4+
#include "common.hpp"
5+
6+
struct Base {
7+
virtual void f() = 0;
8+
virtual void g() = 0;
9+
virtual void h(int) = 0;
10+
void i() {}
11+
};
12+
13+
struct Derived : Base {
14+
void f() override;
15+
void g() override {};
16+
17+
void h(int) {};
18+
#if 1
19+
void h(float) {};
20+
#else
21+
// g++6.4.0: error: ‘void Derived::h(float)’ marked ‘override’, but does not override
22+
void h(float) override {};
23+
#endif
24+
25+
#if 1
26+
void i() {}
27+
#else
28+
// g++6.4.0: error: ‘void Derived::i()’ marked ‘override’, but does not override
29+
void i() override {}
30+
#endif
31+
};
32+
33+
#if 1
34+
void Derived::f() {}
35+
#else
36+
// g++6.4.0: error: virt-specifiers in ‘f’ not allowed outside a class definition
37+
void Derived::f() override {}
38+
#endif
39+
40+
int main() {
41+
Derived derived;
42+
43+
// Yup, it is a valid identifier in normal contexts.
44+
int override = 1;
45+
}

0 commit comments

Comments
 (0)