Sam12
Sam12

Reputation: 1805

Copy string in C++

I would like to convert this constructor's argument from const char* to std::string, but I don't know how to copy the new name to name properly.

Player::Player(const char* name) :
        level(1),life(1),strength(1),place(0){
    char* new_player_name = new char[strlen(name) + 1];
    strcpy(new_player_name, name);
    this->player_name = new_player_name;
}

Player::Player(string name) :
        level(1),life(1),strength(1),place(0){
    string new_player_name(' ',name.length() + 1); //#1
// I didn't know how to proceed 
}

The classes data-members:

class Player {
    char* player_name;
    int level;
    int life;
    int strength;
    int place;
};

Upvotes: 1

Views: 1826

Answers (1)

Bathsheba
Bathsheba

Reputation: 234875

Consider making player_name a std::string.

Then your constructor could start

Player::Player(const char* name) : player_name(name)
{

and you don't need to fiddle about with all those dynamically allocated char arrays.

You could change the type of name to a const std::string& too:

Player::Player(const std::string& name) : player_name(name)
{

Upvotes: 7

Related Questions