Skip to content

Commit c504e6d

Browse files
committedDec 13, 2017
const class objects and functions
1 parent 744b66f commit c504e6d

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed
 

‎FunctionOverloading.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@ int main () {
2828
const Person p2; //used to access the const member function
2929

3030
cout<<p2.x<<endl;
31-
// p2.x=20; with a const object, its data members can never be changed till the lifetime of object.
32-
31+
//p2.x=20; with a const object, its data members can never be changed till the lifetime of object.
32+
3333

3434

3535
//1) non-const object of class can be used to call and access the const members(variables and methods) of a class,but.

‎constClass.cpp

+58
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
#include<iostream>
2+
3+
using namespace std;
4+
5+
//const objects and const member functions
6+
7+
class Person {
8+
public:
9+
//const class data member
10+
int age;
11+
string name;
12+
//constructor
13+
Person(int iage,string iname){
14+
//age=iage; //initializing const data age using constructor
15+
age=iage;
16+
name= iname;
17+
}
18+
19+
void getage() 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+
void getname() { //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+
int main () {
36+
37+
Person p(20,"anish");
38+
Person const p1(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
50+
51+
52+
53+
54+
55+
56+
return 0;
57+
58+
}

0 commit comments

Comments
 (0)
Please sign in to comment.