0

Need some help here it seems to compile fine but crashes at runtime. Am I missing something here?

#include <iostream>
#include <string>
using namespace std;

// player class
class Player{
	int *position;
public:
	Player();
	Player(int);
	~Player();
	void print_pos(){
		cout << "player 1 is in position: " << *position << endl;
	}
};

Player::Player(){ // main constructor
	position = new int;
	*position = 0;
}
Player::Player(int pos){  //overloaded constructor
	*position = pos;
}
Player::~Player(){ // destructor
	delete position;
}


int main()
{
	Player one;
	Player two(1);
	one.print_pos();
	two.print_pos();
	return 0;
}
2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by predator78
1

Look at your "overloaded" constructor. Does it allocate memory? Does it dereference the pointer as if memory were allocated?

Votes + Comments
excellent
0

Thank you very much I'm learning very fast why c++ guru's are so precise about every minor detail.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.