Reputation: 1612
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.
Upvotes: 4
Views: 1118
Reputation: 126
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.
Upvotes: 0
Reputation: 258548
The const
version will only be called on a const
object.
const test t;
t.data();
Upvotes: 4
Reputation: 227370
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();
Upvotes: 10