-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path46_Protected_Members.cpp
More file actions
75 lines (57 loc) · 1.81 KB
/
46_Protected_Members.cpp
File metadata and controls
75 lines (57 loc) · 1.81 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
#include <iostream>
using namespace std;
/*
From encapsulation chapter:
The access modifier "protected" is especially relevant when it comes to C++ inheritance. Same as private members, protected members are inaccessible outside of the class. However,
they can be accessed by derived classes and friend functions/classes. The protected members is needed, if we want to hide the data of a class, but still want that data to be inherited
by its derived class(es).
*/
class Animal {
private:
string color;
protected:
string type;
public:
void eat(){
cout << "Eating!" << endl;
}
void sleep(){
cout << "Sleeping!" << endl;
}
void setColor(string clr){
color = clr;
}
string getColor(){
return color;
}
};
class Dog : public Animal {
public:
//type is protected ad is thus accessible from Dog class.
//Also, since the protected keyword hides data, type cannot be accessible directly (setType)
void setType(string tp){
type = tp;
}
//color attribute from Animal class is private, so cannot be initialized like type in Dog class
/*
void setColor(string clr){
color = clr;
}
//this method (setColor) causing an error
*/
void displayInfo(string c){
cout << "It's a " << type << " in color " << c << endl;
}
void bark(){
cout << "The dog is barking!" << endl;
}
};
int main(){
Dog dog;
dog.eat();
dog.sleep();
dog.setColor("Brown");
dog.bark();
dog.setType("Shiba"); //dog.type = "Shiba" causing an error
dog.displayInfo(dog.getColor());
}