C++ has some interesting keywords that allow you to do different things. For example, if you want to make sure that you don’t accidentally change any values in a method, you can use the const
keyword.
Now this is similar to how you use it on a parameter for a function, but since you don’t pass in instance variables, you can do it on the method.
It’s quite simple – all you need to do is add const
to the end of the method prototype, but before the semi-colon. This is great for methods like your getters, where you shouldn’t be changing any values, and keeps you from accidentally making mistakes.
#pragma once
class Circle
{
public:
Circle();
Circle(double newRaidus);
double getArea();
double getDiameter() const;
double getRadius() const;
void setRadius(double newRadius);
private:
double radius;
};
If you have your Class separated out into external files, then you will need to place const after the method name in the .cpp file as well.
Methods that Can’t Change Values was originally found on Access 2 Learn