public class member modifies private member via pointer, runtime crash

Jul 28, 2010 at 6:11pm
I've stripped it down to short files illustrating the issue (I was actually hoping to find the issue, but it didn't happen). I'm sure I'm missing some basic concept here, but I'm at a loss so any help would be appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//main.cpp
#include <cstdlib>
#include <iostream>
#include "overworld.h"

using std::cout;
using std::cin;

int main(int argc, char *argv[])
{
    Overworld (theGame);
    short unsigned exitStatus = theGame.arenaExterior();
    return exitStatus;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//overworld.h
#include <iostream>
#include <cstdlib>
#include "player.h"

class Overworld
{   
    private:
        Player* pTheUser;
    
    public:
        Overworld();
        ~Overworld();
        short unsigned arenaExterior();
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//overworld.cpp
#include <iostream>
#include <cstdlib>
#include "overworld.h"

Overworld::Overworld()
{
    Player *pTheUser = new Player();
}

Overworld::~Overworld()
{
}

short unsigned Overworld::arenaExterior()
{
    pTheUser->levelUp();
    return 0;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//player.h
#include <iostream>
#include <cstdlib>

class Player
{
    private:
        short unsigned pLevel;
    
    public:
        Player();
        ~Player();     
        void levelUp();                        
};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//player.cpp
#include <iostream>
#include <cstdlib>
#include "player.h"

Player::Player()
{
    pLevel = 1;
}
Player::~Player()
{
}
void Player::levelUp()
{
    pLevel++;
}
Last edited on Jul 28, 2010 at 6:11pm
Jul 28, 2010 at 6:16pm
Class Overworld should have user defined copy constructor and operator=
Jul 28, 2010 at 6:40pm
I'm not sure how to do that but at least I have something to read up on now. Thanks.
Jul 28, 2010 at 9:28pm

1
2
3
4
5
6
7
8
9
Overworld::Overworld()
{
    //This is a  local variable called pTheUser - not the class member of the same name.
    //This local variable will dissapear once the constructor finishes, which is what causes the
    //Overworld::arenaExterior() function to crash (plus it also creates a memory leak)

    Player *pTheUser = new Player();
}
Aug 9, 2010 at 9:36pm
Looking at this now, I truly have no idea what I was thinking. Thanks for pointing me in the right direction.
Topic archived. No new replies allowed.