[prog] C++ const method & static_cast

Dan Richter daniel.richter at wimba.com
Mon Mar 22 09:51:23 EST 2004


>    I am trying to switch all my getters to const:
<snip>
>    This line fails at linking:
> undefined reference to `Tab::getPrevious()'

I see two possible sources of trouble.

First, when you declare a method as const, you have to declare the 
implementation as const as well:

class Tab {
   Tab *getPrevious() const;
};

Tab* Tab::getPrevious() const /* "const" here too! */ {
   return foo;
}

This is because you can actually define two methods with the same 
signature except that one is const and the other is not:

class Tab {
   Tab *getPrevious();
   Tab *getPrevious() const;    // Not an error.
};

At least, I know you can do that for operator overloading, and I believe 
you can do that for any method.

The second potential problem is that if getPrevious() is const, then any 
pointer to a member that it returns must be const. For example:

class DataStore {
   Data *data;
   Data *getData() const { return data; }    // Error!
   const Data *getTheData() const { return data; }    // OK
};

This is an error because it would allow you to change the content of a 
const class like this:

   void Foo(const DataStore* store) {
     DataStore *stuff = store->getData();
     stuff->first_part = new_value;
     ...
   }

The const is strongly enforced in C++. If you are going to return a 
pointer to a member from a const method, it has to be const.

One more thing: this strong enforcement of the const in C++ means that 
you'll find it quite a pain to add it to an already complete program.

-- 
  [Larry] Wall [inventor of Perl] believes that people think about
  things in different ways, that natural languages accommodate many
  mindsets, and that programming languages should too.
    - Jon Udell, in his essay, "A Perl Hacker in the Land of Python"



More information about the Programming mailing list