CPB Mailing List
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: const keyword position
Hi Tay,
The 'const' keyword is a type modifier that's good for a lot of things.
Its behavior depends on the context in which it appears. Here are some
examples:
1. Declaring constants
const NumberOfItems = 10;
In this case, NumberOfItems is NOT a variable. The compiler substitutes
10 for NumberOfItems. Constants in C++ are similar to the #define
definitions, but while #define's are processed in the first phase by the
preprocessor, const's are processed in the second phase by the compiler.
2. Declaring a constant variable
const int x = 10;
Variable x cannot be written, it's read only. In most cases, const
variables are used in a function parameter, for instance:
int foo(const char* s);
The foo function can't write the input string s, it can only read it.
Note that the const refers not to the pointer itself. Variable s can
still be incremented, decremented, or whatever, but *s cannot be an
lvalue. So the const makes *s read-only. If you wanted to make the
pointer read-only, you should have written char* const s. In this case,
you could modify *s, but you wouldn't be able to modify s. To make both
s and *s read-only, just write const char* const s.
3. Returning constant objects
const char* foo();
The foo function returns a constant variable. If you write *foo()='A',
then you'll get an error message "Cannot modify a const object."
4. Constant member functions
Consider the following class:
class TClass
{
private:
int x;
public:
TClass() { }
void SetX(int value) { x = value; }
int GetX() const { return x; }
};
SetX member function sets the private member variable x, while GetX
returns x. GetX is a constant member function, because it doesn't modify
any object in the class. Each function that doesn't modify any object in
the class should be declared const. A const member function cannot write
any member functions in the class. Only the const member functions can
be called for a const object. Example:
const TClass MyObject;
MyObject.GetX(); // Ok
MyObject.SetX(10); // error!
Only member functions can be declared const. There is no such thing as
const funtion.
I suggest you read The C++ Programming Language by Bjarne Stroustrup.
Tom
W Komornicki's Home Page |
Main Index |
Thread Index