You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//age=iage; //initializing const data age using constructor
15
+
age=iage;
16
+
name= iname;
17
+
}
18
+
19
+
voidgetage() const {
20
+
21
+
cout<<"My age is-"<<age<<endl;
22
+
//age++; produces error as inside a const member function data members of class become const too and value cannot be changed once declared
23
+
24
+
}
25
+
26
+
voidgetname() { //a non const function which cannot be called by a const object
27
+
28
+
age++;
29
+
cout<<"My name is :"<<name<<endl;
30
+
31
+
}
32
+
};
33
+
34
+
35
+
intmain () {
36
+
37
+
Person p(20,"anish");
38
+
Person constp1(30,"Mrinal"); // a const object and a data member cannot be changed using a const object throughtout its lifetime
39
+
40
+
p.getage(); //const member function can be called using non-const object too.
41
+
p.getname();
42
+
p.age=25;
43
+
p.getage();//value of age is now 25
44
+
45
+
//using const object only for const member functions
46
+
p1.getage();
47
+
// p1.age=25; produces ERROR as when using a const member object,the class data members become constant too i.e read-only and cannot be changed once initialized
48
+
49
+
//p1.getname(); ERROR as const object cannot call a non-const member function
0 commit comments