I am learning, a little late, about const correctness and have found some strange behavior which I just don't understand. I wrote a class which has a std::list of ints, & a method to return a bool, true if the list contained the int given as the method's argument. It seemed obvious that it could get const at the end, since it was not changing anything about the object.
However, I moved the method into the .cpp file and suddenly the compiler refused to identify "bool hasThisInt( int const inputInt ){...}" in the .cpp file with its prototype "bool hasThisInt( int const inputInt ) const;" in the header. If I removed the const at the end of the prototype, the compiler stopped complaining. However, now the method counts as a mutable, so this is not ideal (since, as you might guess, this is actually a toy example for a larger, more complicated program).
Is this related to the issues preventing template classes being split across headers and source files? Or is it some peculiarity of my compiler? I am using g++ 4.2 on Ubuntu, through Eclipse Helios with the C++ IDE 1.3.1.
Just to recap:
it works if the method is split across header and source, as long as it is not declared const;
it also works if the method is entirely in the header and declared const;
but it does not work if the method is split across header and source while also declared const.
Thank you very much for your answers,
Ben O'Leary (Hey, why does bytes.com hate Irish names? Any attempt to put some sort of indicator in its place results in an invalid name too.)
Here is the offending code:
Expand|Select|Wrap|Line Numbers
- in the header file inspectionExample.h:
- #ifndef INSPECTIONEXAMPLE_H_
- #define INSPECTIONEXAMPLE_H_
- #include <vector.h>
- class inspectionExample
- {
- public:
- inspectionExample( int x,
- int y,
- int z );
- virtual
- ~inspectionExample();
- bool
- hasThisInt( int const inputInt )
- const
- {
- bool returnBool = false;
- for( std::vector< int >::const_iterator intIt = ints.begin();
- ints.end() > intIt;
- ++intIt )
- {
- if( inputInt == *intIt )
- {
- returnBool = true;
- }
- }
- return returnBool;
- }
- protected:
- std::vector< int > ints;
- };
- #endif /* INSPECTIONEXAMPLE_H_ */
- (end of inspectionExample.h)
- If I move hasThisInt to inspectionExample.cpp, this is what is in the source file
- (the constructor and destructor are here in any case):
- #include "inspectionExample.h"
- inspectionExample::inspectionExample( int x,
- int y,
- int z )
- {
- ints.push_back( x );
- ints.push_back( y );
- ints.push_back( z );
- }
- inspectionExample::~inspectionExample()
- {
- // does nothing.
- }
- bool
- inspectionExample::hasThisInt( int const inputInt )
- {
- bool return_bool = false;
- for( std::vector< int >::const_iterator intIt = ints.begin();
- ints.end() > intIt;
- ++intIt )
- {
- if( inputInt == *intIt )
- {
- return_bool = true;
- }
- }
- return return_bool;
- }
- (end of inspectionExample.cpp)