I am reading Effective C++ which tells me that 'member functions differing only by their constness can be overloaded'.
The book example is:
class TextBlock {
public:
const char& operator[](std::size_t position) const;
char& operator[](std::size_t position);
private:
std::string text;
}
My example below, uses a stored pointer.
class A {
public:
A(int* val) : val_(val) {}
int* get_message() { return val_; }
const int* get_message() { return val_; } const;
private:
int* val_;
};
I get:
error C2556: 'const int *A::get_message(void)' : overloaded function differs only by return type from 'int *A::get_message(void)'
What is the difference? Is there any way I can fix the class so I have a const and non-const version of get_message?
You're putting the const
qualifier for your get_message()
function in the wrong place:
const int* get_message() const { return val_; }
// ^^^^^
// Here is where it should be
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With