View Single Post
Old 05-14-2005, 11:40 AM   #1 (permalink)
Valmont
[code][/code] enforcer
 
Valmont's Avatar
 
Join Date: Mar 2003
Location: Netherlands
Posts: 1,544
Valmont is on a distinguished road
TIP (5 minute read): remainder on const objects

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;
}
__________________
Valmont is offline   Reply With Quote