Recap On const Methods
A
const method is to be declared if this method is not allowed to modify the pointer
this.
Example:
Code:
class AClass
{
public:
//Must implement a constructor otherwise no const(ant) instance is allowed.
AClass() {}
void DoStuffNonConst()
{
}
void DoStuffConst() const
{
}
};
DoStuffConst() won't be allowed to modify any members.
So far the recap.
Enforcing const(ness) of objects
One may want to create and intialize a const object:
Code:
const AClass theConstObject;
To enforce the
constness of this object, this object may only call const methods:
Code:
class AClass
{
public:
//Must implement a constructor otherwise no const(ant) instance is allowed.
//Remember, const objects *must* be intialized. Hence the constructor.
AClass() {}
void DoStuffNonConst()
{
}
void DoStuffConst() const
{
}
};
int main()
{
const AClass theConstObject;
theConstObject.DoStuffNonConst(); // ILLEGAL.
theConstObject.DoStuffConst(); // LEGAL.
return 0;
}