K
Kira Yamato
It is erroneous to think that const objects will have constant behaviors too.
Consider the following snip of code:
class Person
{
public:
Person();
string get_name() const
{
Randomizer dice; // Randomizer is some class that returns random strings.
return dice.getRandomString();
}
void set_name(const string &name);
};
void func(const Person &person)
{
// note that the object 'person' is declared const, so it is immutable.
// However, the following two lines can print different names,
// even though we are invoking const member function 'getName'.
// print one name here,
cout << person.get_name() << endl;
// but it could print a different name here.
cout << person.get_name() << endl;
}
Thus, object behavior is not guarantee to be constant for const object
even though its state is unchanged.
This also means that compiler cannot make optimizations with const object.
So to me, declaring an object 'const' is really just a mechanism to
allow a certain subset of the object's member functions to be called
(those that are declared 'const') and disallow calling the other member
functions, (those that are not declared 'const'). No other conditions
can be assumed.
Consider the following snip of code:
class Person
{
public:
Person();
string get_name() const
{
Randomizer dice; // Randomizer is some class that returns random strings.
return dice.getRandomString();
}
void set_name(const string &name);
};
void func(const Person &person)
{
// note that the object 'person' is declared const, so it is immutable.
// However, the following two lines can print different names,
// even though we are invoking const member function 'getName'.
// print one name here,
cout << person.get_name() << endl;
// but it could print a different name here.
cout << person.get_name() << endl;
}
Thus, object behavior is not guarantee to be constant for const object
even though its state is unchanged.
This also means that compiler cannot make optimizations with const object.
So to me, declaring an object 'const' is really just a mechanism to
allow a certain subset of the object's member functions to be called
(those that are declared 'const') and disallow calling the other member
functions, (those that are not declared 'const'). No other conditions
can be assumed.