by John
Kopp
Introduction Welcome to About.com's
free tutorial on C++ programming. This lesson deals with two
important keywords, const and mutable, and their use with class objects.
Const provides a way to declare that an object is not
modifiable. It can also be used with class methods to indicate
to they will not modify their objects. The use of "const" can
reduce bugs within your code by allowing the compiler to catch
unintended modification of objects that should remain
constant. The keyword mutable provides a way to allow
modifications of a particular data members of a constant
objects. By the way, I love tabloid style headlines, which is
why this lesson is titled "Mutable Members" rather than
something dull like "Const and Mutable"
Const In an earlier lesson, the keyword
const was used to declare that an object of built-in type,
that is, an ordinary variable, was a constant. Attempts to
modify a "const" result in a compilation error.
const int limit; limit =
25; // Results in compilation
error | Assigning
to a const variable is not permitted. It must be initialized
to provide a value.
This
provided a way to have a constant and to be sure that the
constant was not modified unintentionally. C++ also allows the
declaration of const class objects.
// Class Definition class Employee
{ public: string
getName(){return _name;} void
setName(string name) {_name =
name;} string getid(){return
_id;} void setid(string id)
{_id =
id;} private: string
_name; string
_id; };
const Employee john;
| This declares the object john of
class Employee to be constant. But there are problems with
this code. First, since the object is const, we need a way to
initialize it. Its members
cannot be assigned either directly or indirectly via methods. The compiler's default
constructor is insufficient, so we must define constructors
that can initialize all the data members. A default
constructor that initializes all members is required. Other
constructors may be written. Second, C++ allows methods to be
declared as const. By declaring a method "const" we are in
effect stating that the method cannot change its object.
Only methods declared const can be called be a const
object. This has real benefit. The compiler can check
that methods declared const do not modify the object. Attempts
to modify an object within a const method will be flagged by
the compiler. Since a const object may invoke only const
methods, it will not be modified unintentionally. Objects
that are not const can invoke both const and non-const
methods. Which methods should be declared as const?
Certainly, any method that is intended to simple return the
value of a data member should be. Depending upon their
purpose, the const keyword may be appropriate for other
methods as well. Let's correct the Employee class to allow its
proper use with const Employee objects and see its use in a
simple program.
Next
page > Const,
Continued > Page 1,
2,
3
|