Returning a Class Object

I seem to be having difficulty passing a class object back to another function.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
void menu(){
	vector<int> x;
	deque<character> characters;
	character temp("", x);
	int selection;
//This comment replaces cout statments that have nothing to do with the issue.
	switch (selection){
		case 1:
			temp = newCharacter();
			characters.push_front(temp);
			menu();
			break;
//This comment replaces cases that have nothing to do with the issue.
	}
}

character newCharacter(){
	vector<int> stats;
	int temp;
	string name, statNames[9] = {"Void Ring", "Stamina", "Will", "Reflex", "Intelligence", "Strength", "Perception", "Agility", "Awareness"};
	cout << "Character Name: ";
	cin >> name;
	for(int i = 0; i < 9; i++){
		cout << "Enter the character's " << statNames[i] << ": ";
		cin >> temp;
		stats.push_back(temp);
	}
	character newChar(name, stats);
	return newChar;

}


I can compile, but I get a segmentation fault at run time, using:
g++ -Wall main.cpp

I'm almost certain that my problem is the deconstruction of my class object, which is causing temp to be empty, therefore not allowing it to push_front the object the the deque, but I don't know how to get around it. Any ideas?
What are you talking about? "temp" cannot be "empty"; it is an instance of the class, so push_front() won't fail because of that. Where exactly are you getting the segfault (what line, and surrounding code)? Segfaults tend to happen when you access memory you don't own, either with bad pointers or out of bounds on arrays.

$>g++ -Wall main.cpp
$>./a.out
Segmentation Fault
$>


Maybe I should be more clear. With character newCharacter() ending, newChar goes out of scope, which I suspect is causing
 
temp = newCharacter();

to fail.
Last edited on
You haven't answered my question. Start up you debugger and figure out where exactly it is segfaulting.
Okay, I fired up gdb, and ran the program in it. The seg fault showed me the top line in my constructor

0x08048ff0 in character::character (this=0xbffff268, name=..., stats=...) at main.cpp:32		ringVoid = stats[0];

which was independently tested as correct. This confused me for a few minutes, but then
Zhuge: "or out of bounds on arrays"
hit me, and I realized that a vector is a different type of array, meaning it's a pointer to an object which contains multiple (in this case) integers, but that I hadn't initialized the vector. So I changed
1
2
3
4
	vector<int> x;
	deque<character> characters;
	character temp("", x);
	int selection;

to
1
2
3
4
5
	vector<int> x(9);
	for(int i = 0; i < 9; i++){x[i] = 0;}
	deque<character> characters;
	character temp("", x);
	int selection;

and the result was that the class was constructed properly.
Topic archived. No new replies allowed.