How to pass a c-style string into a fucntion that take a C++ string?

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(const char [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.


1
2
3
4
5
6
7
8
9
10
#include <string>
#include <iostream>

int main()
{
  char cStyleString[] = "Beans on toast";
  std::string cPlusPlusString(cStyleString);
  std::cout << cPlusPlusString;
  return 0;
}

Last edited on
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());	
	}
}
Last edited on
Ok, You guys are great. I went into my hierarchy and changed all string& name to const string& name. It works now.


If you notice my method AlloC_Cstring(char*& name, int size) I was wondering if it will work correctly. The code looks like this:

1
2
3
4
5
6
7
void CreatureClass::Alloc_Cstring(char*& cString, int size) { 

	if (cString != NULL) 
		delete[] cString;

	cString = new char[size + 1]; 
}	



Basically I just use it to allocate storage for a char*. Will it work correctly as long as my destructor deletes whatever char*'s I pass in?
Last edited on
Yes, that will work.

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).
Last edited on
Topic archived. No new replies allowed.