Categories: MSDN / DotNet / Java / Scripts / Linux / PHP Ask - La ask - La Answer

Two "error C2440: return : cannot convert"

Its been a while since I've done much in c++, and can't seem to resolve the error I'm receiving in the code below. Any suggestions are greatly appreciated!

#define STRINGSIZE 180

class Color
{
private:
char cString[STRINGSIZE];
public:
Color();
void setColor(char *cs) { *cString = *cs; }
char *getString(void) const { return cString; } /* error C2440: 'return' : cannot convert from 'const char' to 'char *'
Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast*/

Color &operator=(const Color &c)
{
Color newColor;
newColor.setColor(c.getString());
return newColor;
}
};
[788 byte] By [dalegribble] at [2007-11-11 10:30:17]
# 1 Re: Two "error C2440: return : cannot convert"
I think you should add "const":
const char * getString() const { return cString; }
This probably requires one more change:
void setColor(const char *cs) { . . . }
(Note that the body of your setColor function does not seem to copy strings).

I hope this helps.
Viorel at 2007-11-11 20:58:41 >
# 2 Re: Two "error C2440: return : cannot convert"
use char *cString in lieu of
char cString[STRINGSIZE];
allocate memory in constructor and free it in destructor
it career at 2007-11-11 20:59:41 >
# 3 Re: Two "error C2440: return : cannot convert"
you need to return const char* from a function that is declared as const:
const char *getString() const { return cString; } /*

BTW, (void) as a function parameter makes sense only in C. In C++, () will do.
Danny at 2007-11-11 21:00:41 >
# 4 Re: Two "error C2440: return : cannot convert"
Thanks for all of your suggestions. I changed:

char *getString(void) const { return cString; }

to

const char *getString(void) const { return cString; }

and alseo char[STRINGSIZE] to *char and am no longer getting the previous error. However, I doubt my constructor is correct, and in addition to this, how should I set my setColor function to copy strings?

Color(int initSize = STRINGSIZE);

Color::Color(int initSize)
{
cString[initSize];
}
dalegribble at 2007-11-11 21:01:46 >