Hey, could someone give me a brief explanation of what exactly const protects here?
1 2 3 4 5 6 7
class Bacon
{
public:
Bacon(int a) : amount(a) {}
int tellAmount() const {return amount;} ////this const
private:
int amount;
I understand that a const on the return type protects the returned object from being manipulated (right?). I remember learning that the 2nd const after the arguments is supposed to protect the invoking object somehow, but I just can't seem to figure a scenario where the object could be altered when the tellAmount() would be called.
Is it to protect returned references?
Could someone give a simple code example of how this 2nd const would foil an attempt to alter the object?
Thanks.
It tells you that you can use that method with a constant object of that class
1 2 3 4 5 6 7 8 9 10 11 12
class A{
public:
A(){}
void foo() const{}
void bar(){}
};
int main(){
const A a;
a.foo(); //ok
a.bar(); //compile error: no matching function for call to 'A::bar() const'
}
By specifying a member function as const, you are essentially promising that nothing in the class will be changed by that member function (excluding static and mutable members). This is useful for passing const references (shown below) when you don't want an object to be changed, but you don't mind if it's "read."
It is very important to be const-correct in these cases.
#include <iostream>
class Object
{
private:
int var;
public:
Object() : var(0) { }
void setVar(int val) { var = val; } // Can change anything it wants
int getVar() const { return var; } // Promises not to change anything
};
void printObject(const Object&); // printObject can only call const members in the object
int main()
{
Object obj;
obj.setVar(12345);
printObject(obj);
return 0;
}
void printObject(const Object& obj)
{
//obj.setVar(-1); // Will throw a compiler error if uncommented
std::cout << "The object's value is " << obj.getVar() << std::endl;
}