Changes to data inside class not being shown when accessed from outside class.
Posted
by Hypatia
on Stack Overflow
See other posts from Stack Overflow
or by Hypatia
Published on 2010-05-03T22:08:20Z
Indexed on
2010/05/03
22:18 UTC
Read the original article
Hit count: 168
I have two classes, Car and Person. Car has as one of its members an instance of Person, driver. I want to move a car, while keeping track of its location, and also move the driver inside the car and get its location. However, while this works from inside the class (I have printed out the values as they are calculated), when I try to access the data from main, there's nothing there. I.e. the array position[] ends up empty. I am wondering if there is something wrong with the way I have set up the classes -- could it be a problem of the scope of the object?
I have tried simplifying the code so that I only give what is necessary. Hopefully that covers everything that you would need to see. The constructer Car() fills the offset array of driver with nonzero values.
class Car{
public:
Container(float=0,float=0,float=0);
~Container();
void move(float);
void getPosition(float[]);
void getDriverPosition(float[]);
private:
float position[3];
Person driver;
float heading;
float velocity;
};
class Person{
public:
Person(float=0,float=0,float=0);
~Person();
void setOffset(float=0,float=0,float=0);
void setPosition(float=0,float=0,float=0);
void getOffset(float[]);
void getPosition(float[]);
private:
float position[3];
float offset[3];
};
Some of the functions:
void Car::move(float time){
float distance = velocity*time;
location[0] += distance*cos(PI/2 - heading);
location[1] += distance*sin(PI/2 - heading);
float driverLocation [3];
float offset[3];
driver->getOffset(offset);
for (int i = 0; i < 3; i++){
driverLocation[i] = offset[i] + location[i];
}
}
void Car::getDriverPosition(float p[]){
driver.getPosition(p);
}
void Person::getPosition(float p[]){
for (int i = 0; i < 3; i++){
p[i] = position[i];
}
}
void Person::getOffset(float o[]){
for (int i = 0; i < 3; i++){
o[i] = offset[i];
}
}
In Main:
Car * car = new Car();
car->move();
float p[3];
car->getDriverPosition(p);
When I print driverLocation[] inside the move() function, I have actual nonzero values. When I print p[] inside main, all I get are zeros.
© Stack Overflow or respective owner