Initializing Vectors within a Class

I have a class definition as follows:

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
36
37
38
39
40
41
42
43
//Scene.h
class Scene{
   vector <Sphere> objects;

public: 
   void addSphere(Sphere s);
   vector<Shape> getSpheres();
};

//Scene.cpp
void Scene::addSphere(Sphere s){
  objects.push_back(s);
}
vector<Sphere> Scene::getSpheres(){  
  return objects;
}


//I have another class:

//ReadInput.h
class ReadInput{
   Scene scene;
public:
   void readScene();
};

//ReadInput.cpp
void readScene(){
   //Read from an input file
   Sphere sphere(center,radius);
   scene.addSphere(sphere);
}

void getSphere(){
   scene.getSpheres.at(0);
}


//In my main file
ReadInput r;
r.readScene();
cout << r.getSphere.radius << "\n";


However, when I get to the output line, I don't get the radius I read into the object. I think there's something wrong with my memory management, but I'm not sure.

Does anyone have any insight into the problem? I'm a bit of a C++ newbie.
You've omitted quite some stuff that could be vital. Is the data being read correctly? Is your Sphere constructor working properly? Also, this seems a bit excessive:

1
2
3
4
5
6
7
vector<Sphere> Scene::getSpheres(){  
  return objects;
}
//...
void getSphere(){
   scene.getSpheres.at(0);
}

Probably more efficient to have getSphere(int i) return a single Sphere rather than copying an entire vector just to access a single Sphere...
Is that your real code? if getSphere is a function you can't do r.getSphere.radius. When you declare readScene you forgot to add ReadInput::. Is getSphere() meant to be a member of ReadInput?
All the data is being read correctly. The sphere constructor is working properly because I've run some tests where I create an object, push it in the vector, and in the same function call, read it from the vector and all the values are right.

This isn't the real code - it's just an abstraction of what I'm trying to do. Sorry if that's unclear.

Basically, I'm trying to determine if I need to do anything special for the vector I'm declaring in Scene. In the real code, I define other variables whose values are retained throughout the execution of my program.

However, for the Spheres vector, the Sphere object is only accurate within the function call where the Sphere is being created. So, for:

1
2
3
4
5
6
7
8
{
..
Sphere s(center,radius);
// s has correct values
scene.addSphere(s);
scene.getSphere();
//scene.getSphere() matches s
}


However, if I were to call getSphere() inside a different function, the sphere returned would NOT match the s that I placed at the beginning of the code.

Is there anything special that I need to do when I'm handling vectors inside of a class definition?

Topic archived. No new replies allowed.