General Question

HeroicZach's avatar

Why does C++ not allow me to use strings in a class header file?

Asked by HeroicZach (195points) September 20th, 2009
2 responses
“Great Question” (1points)

I have code that looks like this:

public:
myClass(string inWord); // value constructor

Up above the class in the class header file, I have #include <string>, so C++ should know what I’m talking about. Unfortunately, I ALWAYS get this error message:

15 myClass.h expected `)’ before “inWord”

Further down in the class, I have:
bool myFunction(string guessWord);
but I get the following error message:
22 myClass.h expected `;’ before ’(’ token

Why is this happening? If I comment out all the references to string the program compiles, and even when I engage some back in, the program starts to compile – it’s only when I create the value constructor in the .cpp file that matches with this .h that the program explodes in errors. Even when I comment out the value constructor implementation in the .cpp file, clean, then recompile, it still explodes in errors until I remove all string references.

Your help is 110% greatly appreciated.

Observing members: 0
Composing members: 0

Answers

HeroicZach's avatar

OK, I think I’ve got this figured out!

I already declared “using namespace std;” in my main.cpp file, but in the .h, I did not, so technically I was supposed to be calling std::string. What a stupid mistake!

HasntBeen's avatar

It’s usually best to limit your use of ‘using namespace’, because in a large program you can easily get naming conflicts that way. In general, the more limited your “name lifting” is, the more flexible and reusable your code will be.

I recommend that you declare myClass as taking std::string. Then, if you want the abbreviated form for convenience within the class, make a member type declaration at the top of the class, e.g.

class myClass {
typedef std::string string;
myClass( string s );

.. The other wrinkle here has to do with performance. It’s better to pass a ‘const string & ) to these functions than an actual string value: this allows the compiler to eliminate the overhead of making a private copy of the string for the function, which is often unnecessary and wasteful:

bool myFunction(const string & guessWord);

Answer this question

Login

or

Join

to answer.

Mobile | Desktop


Send Feedback   

`