-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAbstraction
More file actions
74 lines (59 loc) · 1.96 KB
/
Abstraction
File metadata and controls
74 lines (59 loc) · 1.96 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
Abstract classes are the classes which contains one or more abstract method; and abstract methods are the methods which does not contain any implementation,
but the child-class need to implement these methods otherwise error will be reported. In this way, we can force the child-class to implement certain methods in it.
We can define, abstract classes and abstract method using keyword ‘virtual void’, as shown in Line 27
Since, ‘scarySound’ is defined as abstract method at Line 27, therefore it is compulsory to implement it in all the subclasses.
Note
// abstractClassEx.cpp
#include <iostream>
using namespace std;
class Jungle{
private: // not accessible outside the class
string visitorName;
public: // to allow access to function 'welcomeMessage' outside the class
// setVisitorName is accessible outside the class, which will set the visitor name
void setVisitorName(string name){
visitorName = name;
}
// function to retrieve the visitorName as it is not accessible directly
string getVisitorName(){
return visitorName;
}
// welcome message
void welcomeMessage(){
cout << "Welcome to Jungle " << getVisitorName();
}
virtual void scarySound() = 0;
};
class Animal : public Jungle{
public:
void scarySound(){
cout << "Animals are running away due to scary sound." << endl;
}
};
class Bird : public Jungle{
public:
void scarySound(){
cout << "Birds are flying away due to scary sound." << endl;
}
};
// Now, it is compulsory to define 'scarySound' in Insect as well
class Insect : public Jungle{
public:
void scarySound(){
cout << "Insects do not care about scary sound." << endl;
}
};
int main(){
Animal a;
Bird b;
Insect i;
a.scarySound();
b.scarySound();
i.scarySound();
return 0;
}
/* Outputs
Animals are running away due to scary sound.
Birds are flying away due to scary sound.
Insects do not care about scary sound.
*/