Hi,
Is there a way I could call a constructor for already constructed object?
I have something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int global_val=0;
struct A: public A{
//members...
A(){}
A(int i){
global_val=i;
}
~A(){
global_val=0;
}
};
int main(){
A* obj=new A;
//lots of code...
*obj=A(15);
return 0;
}
This doesn't work, becouse this code creates another object, copies its members and destroys it, so global_val will be 0 in the end.
Of course I could do this with a function Set(int i) but I wanted to know if there is another way.
Is there a way I could call a constructor for already constructed object?
No. One object gets one constructor called once. This keeps things very simple. You technically can side-step this by using placement new, but you really shouldn't -- it'd be a horrible, horrible thing to do.
since global_val is a global variable, why bother using a structure instance to change it? Why not just write global_val = 5;
In this case you just need to create a reasonable interface for your struct or class. Create mutator member functions that can modify its state. That is what public interfaces are for. It has a default assignment operator or you can write your own if necessary depending on whether this class needs one to be written. You can certainly create a reset member function to reset the objects state to its initial values.