Const method accessing private data member giving access violations

My code is here https://www.dropbox.com/s/foq27lafefoes7d/lab3.zip?dl=0

void Player::Display() const
{
cout << "\nPlayer Name: " << GetName() <<
"\nGrade: " << GetGrade() << "\nG.P.A. " << GetGPA() << endl;
}

The problem occurs in here, I get access violations, is there a way to this while keeping Display const or is this code valid and my problem is somewhere else and not being caught in the debugger?
I tried to make the return types const - but that didn't help :(

//Getters need const twice for this to work?
const char* Player::GetName() const {return m_name;}
const int Player::GetGrade() const {return m_grade;}
const double Player::GetGPA() const {return m_gpa;}

more relevant code

class Player
{
public:
char* GetName() const;
int GetGrade() const;
double GetGPA() const;


private:
char* m_name;
int m_grade;
double m_gpa;

};
Last edited on
In Sport::Search()
1
2
3
char * usrName = "j";

cin.getline (usrName,BUFFER);


usrName points to read-only memory. Any attempt to read in it could lead to crash.

If you want to use c-strings for some reasons instead of safe C++ ones, at least make a static buffer:
1
2
3
const int BUFFER = 256;
char usrName[BUFFER];
cin.getline (usrName,BUFFER);


Another problem is that you never adding players to your array. You are adding pointer to the local variable which gets destroyed several lines later. So all your "Get" functions are called on invalid objects.
Do not use manual memory management. For example your array, you always manually reallocate is better replaced by vector of Players, or if you need indirection (why?) by vector of unique_ptr<Player>.

You have way more problems. I just do not want to hunt them all as it would be faster to just rewrite class from scratch.
Last edited on
I think you're using array for the first time without initialising it. The proper place for this is in the constructor.

On the whole though your use of pointers is quite alarming, you seem to be deliberately avoiding safe language features and the standard library. Is there a constraint on you to write this way?
Topic archived. No new replies allowed.