error: 'char* Character::getName()' cannot be overloaded

In my project some methods require a string, while others (like my SDL stuff) require a char* In my code I have this:

character.h
public:
<some other methods>
string getName() { return name; }
char* getName();

Whenever I try running make (actually remake is what I use), it tells me

character.h:60:13: error: 'char* Character::getName()' cannot be overloaded
character.h:59:14: error: with 'std::string Character::getName()'

There HAS to be a reason why I can't overload this method; I just can't figure out what it is...
There is. They take the same number and type of arguments.

They do? I thought one returned a string and the other returned a char*. Surely those two types are different...?
closed account (zb0S216C)
"std::string" accepts a pointer to a "char" as a constructor argument. Because of "std::string"'s conversion constructor, the two prototypes are ambiguous, and the compiler will not be able to determine which overload the caller requested. There's 2 ways to disambiguate a function call:

1) Tagging. Tagging is used to resolve seemingly ambiguous function calls by passing a "tag" to the function. For instance:

1
2
3
4
5
6
struct ResolutionTag { };
struct ConstCharPtrTag : public ResolutionTag { };
struct StringTag : public ResolutionTag { };

std::string Function(StringTag);
char *Function(ConstCharPtrTag);

2) Differentiate the prototypes. A compiler will be able to resolve an ambiguous function call if 2 of the following differ from the other overloads: Return-type, parameters, and function const-ness.

Wazzak
Hang on here. This is getting a little out of hand.

Don't do any of that.

Use strings for everything. Only have functions that return strings. Do not have char*s anywhere.

When you need to interface with SDL, use string's c_str() function. That's what it's for.

1
2
3
4
5
6
7
8
string Character::getName()
{
  // return a string
}

//...

SDL_SomeFunctionThatTakesACharPointer( mycharacter.getName().c_str() );
They do? I thought one returned a string and the other returned a char*. Surely those two types are different...?


The return types have nothing to do with the number and type of arguments the functions take. And, unfortunately, you can't overload on return types.
Topic archived. No new replies allowed.