Const Data Member
- Const data members are constant so that not to be changed once initilized.
- Each object maintains its own copy of const data members in memory, separate from other objects.
Two ways of initialization
1st Way: Initialize in class
#include <iostream>
using namespace std;
class Circle {
public:
Circle(float a) { r = a; }
float getArea() { return r * r * pi; }
private:
const float pi = 3.14;
float r;
};
int main() {
Circle c1(5.2), c2(10);
cout << c1.getArea() << endl;
cout << c2.getArea() << endl;
return 0;
}
2nd Way: Initializer list is used to initialize them from outside
#include <iostream>
using namespace std;
class Phone {
public:
Phone(string str, int a) : pname(std::move(str)), memsize(a) {};
string getPhoneName() {return pname; }
private:
const string pname;
int memsize;
};
int main() {
Phone p1("HUAWEI", 64), p2("IPHONE", 32);
cout << p1.getPhoneName() << endl;
cout << p2.getPhoneName() << endl;
return 0;
}