user1985351
user1985351

Reputation: 4689

Char to char* C++

I'm having an error with my constructor in my classes.

In my .cpp file I've got:

Player::Player()
{

    m_name="Jane";
    m_amt=100;
}

and in my .h file I've got:

// Default constructor, does nothing.
    Player();

    // Creates a Player. Player name and amount.
    Player(const char &name, int amt);

I'm getting the error:

error: invalid conversion from ‘const char*’ to ‘char’ [-fpermissive]
  m_name="Jane";

So I tried converting it to a *char but that still doesn't work. Can someone help please?

Upvotes: 0

Views: 121

Answers (2)

cedoc
cedoc

Reputation: 33

Show your full class/code. Following compiles fine for me.

cpp file...

#include"player.h"

Player::Player()
{
    m_name="Jane";
    m_amt=100;
}

.h file...

class Player {

public:
        // Default constructor, does nothing.
        Player();

        // Creates a Player. Player name and amount.
        Player(const char *name, int amt);

private:
        char* m_name;
        int m_amt;

};

Upvotes: 0

LihO
LihO

Reputation: 42103

You can either take a pointer:

Player(const char* name, int amt) { ... }

and you could use std::string to store the name and use char* just to construct this string:

private:
    std::string m_name;
public:
    Player(const char* name, int amt) : m_name(name) { }

or just use std::string everywhere and pass by reference to avoid redundant copies being created:

private:
    std::string m_name;
public:
    Player(const std::string& name, int amt) : m_name(name) { }

Note that the last version is quite flexible and it's possible to also pass const char* to it, example:

#include <iostream>
#include <string>

class Player {
private:
    std::string m_name;
public:
    Player(const std::string& name) : m_name(name){}
    void printName() { std::cout << m_name; }
};

int main() {
    Player p("Liho");
    p.printName();
}

Upvotes: 3

Related Questions