File tree 1 file changed +9
-6
lines changed
1 file changed +9
-6
lines changed Original file line number Diff line number Diff line change @@ -7,13 +7,14 @@ using namespace std;
7
7
class Person {
8
8
public:
9
9
// const class data member
10
- int age;
10
+ const int age= 20 ; // has to be initialized, when declared, cannot be initialized inside a constructor
11
11
string name;
12
12
// constructor
13
13
Person (int iage,string iname){
14
- // age=iage; //initializing const data age using constructor
15
- age=iage;
16
- name= iname;
14
+
15
+ // age=iage; initializing const data age using constructor produces error
16
+
17
+ name = iname;
17
18
}
18
19
19
20
void getage () const {
@@ -25,7 +26,7 @@ class Person {
25
26
26
27
void getname () { // a non const function which cannot be called by a const object
27
28
28
- age++;
29
+ // age++;
29
30
cout<<" My name is :" <<name<<endl;
30
31
31
32
}
@@ -37,9 +38,11 @@ int main () {
37
38
Person p (20 ," anish" );
38
39
Person const p1 (30 ," Mrinal" ); // a const object and a data member cannot be changed using a const object throughtout its lifetime
39
40
41
+
42
+
40
43
p.getage (); // const member function can be called using non-const object too.
41
44
p.getname ();
42
- p.age =25 ;
45
+ // p.age=25; error produced- age is read only
43
46
p.getage ();// value of age is now 25
44
47
45
48
// using const object only for const member functions
You can’t perform that action at this time.
0 commit comments