I have a constructor that takes a string but my Prof said that if I tried to pass a C-string in that there would be automatic conversion.
But I get this error:
1 2 3
p2.cpp:40:24: error: no matching function for call to ‘CreatureClass::CreatureClass(constchar [5])’
Header/Creature.h:159:3: note: candidates are: CreatureClass::CreatureClass(std::string&)
make: *** [p2.o] Error 1
You can make a proper C++ std::string by feeding a C-style string into the constructor. Use this to make a proper C++ string out of your C-style string, and then use that proper C++ string.
Well, there would be automatic conversion (i.e. casting) if CreatureClass::CreatureClass didn't take a non-const reference to a string. Does CreatureClass::CreatureClass modify the string parameter? If not, you can do CreatureClass::CreatureClass(const std::string& s);
Yes it takes the string and casts it to a c-style string but it doesn't change it, no.
But I want it to work for both.
This what it looks like internally:
1 2 3 4 5 6 7 8 9 10 11 12
CreatureClass::CreatureClass(string& initName) {
if (initName.size() == 0) { // if empty string passed in
Alloc_Cstring(name, D_NAME.size()); // set name to default
name = strcpy(name, D_NAME.c_str());
}
else {
Alloc_Cstring(name, initName.size());
name = strcpy(name, initName.c_str());
}
}
However, be sure that whatever char* you pass in is set to NULL if it's unallocated. The reason I stress this is you're passing in name, which I assume is a member variable, but it is not being set to NULL in the constructor. This can cause a deletion of an unallocated pointer if name is automatically initialized to something that's not zero (this is very likely).