-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathcpp-inheritance.cpp
More file actions
48 lines (37 loc) · 808 Bytes
/
cpp-inheritance.cpp
File metadata and controls
48 lines (37 loc) · 808 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
47
// http://stackoverflow.com/questions/38140630/protected-member-access-works-only-when-not-getting-its-address
#include <iostream>
using namespace std;
class A {
protected:
int x;
public:
A() : x(42) {}
};
class B : public A {
};
class C : public B {
protected:
typedef B Precursor;
public:
void foo() {
//cout << x << endl; // error: ‘x’ was not declared in this scope
cout << Precursor::x << endl;
cout << this->x << endl;
}
int get() {
return Precursor::x;
}
int* getPtr() {
// error: ‘int A::x’ is protected
// error: within this context
// error: cannot convert ‘int A::*’ to ‘int*’ in return
return &Precursor::x;
//return &this->x; // this works
}
};
int main() {
C obj;
obj.foo();
cout << obj.get() << endl;
cout << obj.getPtr() << endl;
}