Skip to content

Commit b8df05d

Browse files
committed
some more description about const class members added
1 parent 38cdf99 commit b8df05d

File tree

1 file changed

+9
-6
lines changed

1 file changed

+9
-6
lines changed

constClass.cpp

+9-6
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,14 @@ using namespace std;
77
class Person {
88
public:
99
//const class data member
10-
int age;
10+
const int age=20;//has to be initialized, when declared, cannot be initialized inside a constructor
1111
string name;
1212
//constructor
1313
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;
1718
}
1819

1920
void getage() const {
@@ -25,7 +26,7 @@ class Person {
2526

2627
void getname() { //a non const function which cannot be called by a const object
2728

28-
age++;
29+
//age++;
2930
cout<<"My name is :"<<name<<endl;
3031

3132
}
@@ -37,9 +38,11 @@ int main () {
3738
Person p(20,"anish");
3839
Person const p1(30,"Mrinal"); // a const object and a data member cannot be changed using a const object throughtout its lifetime
3940

41+
42+
4043
p.getage(); //const member function can be called using non-const object too.
4144
p.getname();
42-
p.age=25;
45+
// p.age=25; error produced- age is read only
4346
p.getage();//value of age is now 25
4447

4548
//using const object only for const member functions

0 commit comments

Comments
 (0)