Is it possible? How do I do it? I need a function to return the players name, so I have this as the prototype:

string getPlayerName();

And this as the function:

string mainFunctions::getPlayerName(){
    return playerName;
}

But I get an error saying that the function called 'string' doesn't have a return type...

I have #included <string> in the header and cpp files.

Dani AI

Generated

Short answer: was right — string lives in the std namespace, so use std::string (or bring std::string into scope with a using in a .cpp only). Since already mentioned adding <string>, the missing piece is usually the namespace qualification or a mismatch between the declaration and the definition.

A safe pattern is to put the #include <string> in the header and declare the function with the exact signature you will define in the .cpp. Example declarations and definitions:

#include <string>

class mainFunctions {
public:
    std::string getPlayerName() const;          // returns a copy
    const std::string& getPlayerNameRef() const; // returns a reference (see warning)
private:
    std::string playerName;
}
#include "mainFunctions.h"

std::string mainFunctions::getPlayerName() const {
    return playerName; // copy; cheap with RVO/move in modern compilers
}

const std::string& mainFunctions::getPlayerNameRef() const {
    return playerName; // only safe while the object exists
}

Quick troubleshooting checklist if the compiler still complains:

  • Make sure the header declaration and the .cpp definition match exactly (qualifiers, const, reference).
  • Avoid using namespace std; in headers — prefer std::string in public headers. See the C++ namespace rules and std::string reference for details (namespaces, std::string).
  • If errors persist, isolate the problem with a minimal example to rule out stray macros, missing semicolons after class definitions, or other unrelated syntax mistakes.

Performance note: returning by value is fine in modern C++ because of copy elision and move semantics. Return a const reference only when the referred object’s lifetime is guaranteed.

Recommended Answers

All 2 Replies

Try using std::string.

commented: Simple working answer, fast reply. +3

Try using std::string.

Thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.