-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconstructor
More file actions
44 lines (32 loc) · 1.42 KB
/
constructor
File metadata and controls
44 lines (32 loc) · 1.42 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
Whenever, the object of a class is create then all the attributes and methods of that class are attached to it; and the constructor (Lines 13-15) is executed automatically.
Note that, the constructor and the class have the same name. Here, the constructor contains one variable
i.e. ‘name’ (Line 13). Therefore, when the object ‘j’ is created at Line 35, the value ‘pranit kharat’ will be assigned to parameter ‘name’ and finally saved in ‘visitorName’ by
the method ‘setVisitorName’ (Line 18)through constructor (Line 14).
#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
// constructor : automatically called at the time of object-creation
Jungle(string name){
setVisitorName(name);
}
// 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;
}
void welcomeMessage(){
cout << "Welcome to Jungle " << getVisitorName();
}
};
int main(){
string name;
Jungle j("pranit kharat"); // 'j' is object of class 'Jungle'
j.welcomeMessage(); // accessing class-function
return 0;
}