capypad
0 day streak
cpp / beginner
Snippet

Const Member Functions for Data Protection

Const member functions (also called const-correctness) promise not to modify any member variables of the class. The 'const' keyword after the function name enforces this contract at compile time. If you try to modify a member inside a const function, the code will fail to compile. This protects your data and makes code easier to understand by clearly indicating which methods are 'read-only'.

snippet.cpp
cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <string>
 
class Circle {
private:
double radius;
 
public:
Circle(double r) : radius(r) {}
double getArea() const {
return 3.14159 * radius * radius;
}
double getCircumference() const {
return 2 * 3.14159 * radius;
}
void setRadius(double r) {
if (r > 0) {
radius = r;
}
}
};
 
int main() {
Circle myCircle(5.0);
std::cout << "Area: " << myCircle.getArea() << std::endl;
std::cout << "Circumference: " << myCircle.getCircumference() << std::endl;
return 0;
}
Breakdown
1
double getArea() const {
Const member function that reads but never modifies member variables
2
return 3.14159 * radius * radius;
Calculates area using the radius - only reads, doesn't write
3
void setRadius(double r) {
Non-const function that intentionally modifies the radius
4
if (r > 0) { radius = r; }
Validation check before modifying the private radius variable