Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C2556: overloaded function differs only by return type

Tags:

c++

constants

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?

like image 377
Angus Comber Avatar asked Dec 07 '22 07:12

Angus Comber


1 Answers

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
like image 83
Andy Prowl Avatar answered Dec 21 '22 23:12

Andy Prowl