const
¶
const
: Immutable Variable¶
Problem:
What if I have a
const
point?This is just the same as getting a
const point*
passed into a function
#include "point-nonconst.h"
#include <iostream>
int main()
{
const point p{2, 4}; // <--- const
double d_orig = p.distance_origin();
std::cout << "distance of (" << p.x() << ',' << p.y() << ") from origin: " << d_orig << std::endl;
return 0;
}
(point-nonconst.h
here
)
code/c++03-const-bogus.cpp:9:38: error: passing ‘const point’ as ‘this’ argument discards qualifiers [-fpermissive]
9 | double d_orig = p.distance_origin();
| ~~~~~~~~~~~~~~~~~^~
code/c++03-const-bogus.cpp:10:40: error: passing ‘const point’ as ‘this’ argument discards qualifiers [-fpermissive]
10 | std::cout << "distance of (" << p.x() << ',' << p.y() << ") from origin: " << d_orig << std::endl;
| ~~~^~
code/c++03-const-bogus.cpp:10:56: error: passing ‘const point’ as ‘this’ argument discards qualifiers [-fpermissive]
10 | std::cout << "distance of (" << p.x() << ',' << p.y() << ") from origin: " << d_orig << std::endl;
| ~~~^~
class point
{
public:
int x() { return _x; } // <---
int y() { return _y; } // <---
double distance_origin() // <---
{
return distance(point{0,0});
}
};
const
Methods¶
A
const
method promises to the compiler that it does not modify the objectNon-
const
: compiler must assume that object is modified ⟶ error (see above)
#ifndef POINT_H
#define POINT_H
#include <cmath>
class point
{
public:
point() = default; // since C++ 11
point(int x, int y) : _x(x), _y(y) {}
// access methods ("getters")
int x() const /* <--- */ { return _x; }
int y() const /* <--- */ { return _y; }
void move(int x, int y) // modifies object, hence non-const
{
_x += x;
_y += y;
}
double distance(point other) const // <---
{
auto a = std::fabs(_x - other._x);
auto b = std::fabs(_y - other._y);
auto c = std::sqrt(std::pow(a, 2) + std::pow(b, 2));
return c;
}
double distance_origin() const // <---
{
return distance(point{0,0});
}
private:
int _x{}; // initialization, since C++ 11
int _y{}; // initialization, since C++ 11
};
#endif
const
Correctness vs. Pollution¶
const
pollution“being correct is very cumbersome”
not using
const
is arrogant (“the compiler cannot help me because I am better”)
Nice goodie offered by the language
Compiler helps me verify that my code is correct
const
correctness