Using const in classes

Remember that const can be used in a variety of places. And everywhere it is applied in code, it:

  1. Expresses an intent on the part of the programmer, which the compiler enforces (i.e. something is not allowed to change, within some scope)
  2. Expresses the intent more clearly to a user (in this case, another portion of code -- i.e. maybe another programmer)
  3. Affects how certain items can be used.

Revisiting const reference parameters


const Member Functions


Declaring const objects


const Member Data


Destructors

In addition to the special Constructor function, classes also have a special function called a destructor.

Declaration:
The destructor looks like the default constructor (constructor with no parameters), but with a ~ in front.  Destructors cannot have parameters, so there can only be one destructor for a class.  Example:  The destructor for the Fraction class would be:

  ~Fraction();

Like the constructor, this function is called automatically (not explicitly)

The destructor's typical job is to do any clean-up tasks (usually involving memory allocation) that are needed, before an object is deallocated.  However, like a constructor, a destructor is a function and can do other things, if desired.

Compile and run this example to see when constructors and destructors are invoked.