4

I've a problem with c++ function overloading. Here is an example class.

class test
{
public:
  const char* data() const
  {
    std::cout << "const char* data() const" << std::endl;
    return data_;
  }

  char* data()
  {
    std::cout << "char* data()" << std::endl;
    return data_;
  }
private:
  char data_[512];
};

In my example I've two function calls.

test t;
const char *t1 = t.data();
char* t2 = t.data();

And my output is char* data() twice. Can someone explain me whats going on? Why is const char* data() const never been called?

Thanks for help.

4
  • 2
    You can't overload on the return value Commented Jan 21, 2014 at 17:12
  • Overloading doesn't magically occur based on what you do with the result down the line. Commented Jan 21, 2014 at 17:14
  • @StoryTeller You can overload on const though AFAIK. I think the problem here is the choice between the two would probably only be affected by the constness of test, or if it was used as a parameter to a function requiring a const parameter (I'm not sure of the latter though). Commented Jan 21, 2014 at 17:14
  • 1
    @Borgleader, you can overload on the constness of this. But the OP was clearly trying to overload on the return value. Commented Jan 21, 2014 at 17:17

3 Answers 3

10

Because t is not const, you get the non-const overload of the method. Note that the constness of the return type does not participate in overload resolution, and you can convert char* to const char*.

If you were to try this

const test t;
const char *t1 = t.data();

you would get the const overload, and this wouldn't compile:

char* t2 = t.data();
Sign up to request clarification or add additional context in comments.

Comments

4

The const version will only be called on a const object.

const test t;
t.data();

Comments

0
test t;
t.data();
static_cast<const test>(t).data();

this will give you the desired results, and you wouldn't need to store it as a temporary as shown in the other answer.

http://ideone.com/XDdacr

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.