Vector of Objects Help

closed account (jvoiNwbp)
Hello everyone. I seem to be having some difficulty with pointers, and vectors of objects. In the example that I will outline below, we are trying to make a human object that is composed of various regions. The head region will have a different number of bones than another region of the body, so I chose to use a vector of bones for each region. The issue is that when I try accessing the 'skull', it's giving me a read access violation error... Anyways, here is the code that is relevant to the question:

Common.h
1
2
3
4
5
6
7
8
9
  #ifndef COMMON_H
  #define COMMON_H

  #include <string>
  #include <vector>

  enum Status {OPERATIONAL,COMPROMISED,STRESSED,FATIGUED,ILL,UNKOWN};

  #endif 


Bone.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#ifndef BONE_H
#define BONE_H

#include "common.h"

class Bone
{
	//TODO: Implement bone

	public:
		Bone();
		Bone(std::string name);
		std::string getName();
		Status getStatus();
		void setStatus(Status in_status);

	private:
		std::string name;
		Status status;
};

#endif 


Region.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#ifndef REGION_H
#define REGION_H

#include "bone.h"
#include "common.h"
#include "muscle.h"
#include "organ.h"


class Region
{
//TODO: Make private and make getters
public:
	std::vector<Bone> bones;
	std::vector<Muscle> muscles;
	std::vector<Organ> organs;
};

#endif


Human.h
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
32
33
34
35
#ifndef HUMAN_H
#define HUMAN_H

#include "region.h"

enum Sex {MALE,FEMALE};

class Human 
{
	public:
		Human();
		std::string getName();
		Sex getSex();
		Region* getHead();

		void setName(std::string in_name);
		void setSex(Sex in_sex);

	private:
		std::string name;
		Sex sex;
		Region* head;
		Region* neck;
		Region* left_arm;
		Region* right_arm;
		Region* thorax;
		Region* abdomen;
		Region* pelvis;
		Region* left_leg;
		Region* right_leg;
};


#endif


and finally...

Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "main.h"

int main()
{
	std::string input = "";
	Human* user = new Human;

	std::cin >> input;
	user->setName(input);

	std::cout << (user->getName());

	std::cout << user->getHead()->bones.at(0).getName();

	system("PAUSE");
	return 0;
}



I know that there's a lot of it, but if anyone has any idea what's going wrong, let me know. Thank you all in advance.
Read http://www.cplusplus.com/doc/tutorial/classes/
and play close attention to default constructors and inheritance.
The problem in your human class is that your pointers are not initialized(created)
Is using pointers a requirement? If not get rid of them and you get rid of many problems.
Topic archived. No new replies allowed.