How to use Const with C++ Classes
Introduction:
Dear students today we will talk about the constant (const) keyword in C++
class structure. In C++ we can use const in a class in three ways;
- const as a data member
- const as a member function
- const ad an object of a class
Important points to remember;
Constant data members can only be assigned by the constant member functions or
by the member initialization list of a constructor. In this example, I am using
member initialization list to assign the values to the constant data member of
class student.
The code snippet is given below;
Code:
////////////////////////////////////////////C++ Code//////////////////////////////////////////////////////////////////
#include <iostream.h>
using namespace std;
class Student
{
const int Rollno;// constant data member
string name;
float cgpa;
public:
Student(int r): Rollno(r),name(""),cgpa(0) //Member initialization list
{
}
int getRollno(){return Rollno;}
};
int main()
{Student obj1(20);
cout << " calling constnt object " << obj1.getRollno()<<endl;
system("pause");
return 0;
}
////////////////////////////////////////////////end////////////////////////////////////////////////////////
Out put
By Hafiz Muhammad Umar Hayat
Email: hafizmohemmedumar@gmail.com

Comments
Post a Comment