Initializing the object members over and over

I need to do calculations inside an object which changes the values of its members. To same memory, I want to write over the objects in the next step of the algorithm and do not create new objects. How can I reinitialize the object members?

Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Foo{
public:
    double A;
    Foo ();
    void add_data (double);
}
Foo::Foo{
    A = 0;
}
void Foo::add_data (double a){
    f.A += a;
}
int main(){
    Foo* foo = new Foo [10000000]; 
    for (int i=0; i<10000000; ++i){
           /*generating data d*/
           foo[i].add_data(d);
    }
/* do some other calculation*/
    for (int i=0; i<10000000; ++i){
           /*generating data d*/
           foo[i].add_data(d);
    }
}

Here I want to initialize the object Foo in the next for loop such that A starts from value 0 again. How can I clear the data added to Foo in the first loop?
Last edited on
Why any member functions at all? Just iterate through the loop and set foo[i].A to 0.

add_data should probably be:

1
2
3
4
void Foo::add_data(double a)
{
    A += a ;
}


Invoked thusly:

foo[i].add_data(d) ;
Last edited on
Dear cire,
I wasn't sure the above definition of add_data adds the data to the right foo. I will fix it as you suggest.
But, there are about hundreds of members in the class and i feel lazy to write them all and set them all to zero. Isn't there a better way, like deconstructing and constructing them again?
make a member function that reset the data.
Your code is wrong rewrite the add_data function to
1
2
3
4
5
6
7
8
void add_data(double a)
{
A+=a;
}
void reset_data()
{
A=0
}

and use the . operator:
1
2
3
4
Foo f;
f.add_data(10);
f.add_data(6);
f.reset_data();
Topic archived. No new replies allowed.