I have an error I've been trying to solve for a while that I can't seem to find a solution to.
Basically what I'm trying to do is create a Player object and store it into a dynamic array of players. I think that part works fine, but in my constructor where I allocate room for the players name, it crashes when I try to copy that into the player data member.. I can't seem to figure out why.
any help would be appreciated!
here's my code:
player.h
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
#ifndef PLAYER_H
#define PLAYER_H
class Player
{
public:
Player(constchar * name, int grade, double gpa); //overloaded
~Player();
bool Search();
void Display();
private:
char * m_Name;
int m_Grade;
double m_Gpa;
};
#endif
The obvious way is to change name = newchar[strlen(name)+1]; to m_Name = newchar[strlen(name)+1]. You should consider using the constructor initialization list to initialize data members where possible.
1 2 3 4 5
Player::Player(constchar * name, int grade, double gpa)
: m_Name(newchar[strlen(name)+1]), m_Grade(grade), m_Gpa(gpa)
{
strcpy(m_Name, name); // this is where it breaks!!
}
And, of course, Zaita is right. Using std::string here would be preferred if you're allowed to use it.
You're going to need a copy constructor and copy assignment operator as well. (If you're using C++11, a move constructor and move assignment operator too.) None of those would be necessary if you were using std::string.