Re: Call constructor in another
On Apr 28, 12:58 am, Blair Craft <lai...@square-enix.net.cn> wrote:
hi,
I got a class have 2 constructors:
You actually have 3, if you don't declare a copy ctor, the compiler
generates one for you ( thats a hint ).
static int g_idx_counter = 0;
[code]
Object::Object():{
counter = g_idx_counter++;
created_at = last_used = time(NULL);
destroyed = false;
id = -1;
}
Use init lists.
// type int is a wild guess, whats type is id?
Object::Object( int n = -1 )
: counter(++g_idx_counter),
created_at(time(NULL)),
last_used(time(NULL)),
destroyed(false),
id(n)
{
}
Object::Object(int _id){
Object();
id = _id;}
The above ctor is not needed, Object() is a local temporary, a
competant compiler would probably optimize it away with no observeable
affect to the result. The above only assigns id.
[/code]
when I use:
Object *o = new Object();
Object* p_obj = new Object;
everything is OK, but when using the second constructor:
Object *o = new Object(32);
member variable "counter" will remain untouched, I did a gdb trace,
Object::Object() was invoked and inside that function "counter" was
initialized, when function returns "counter" went back to 0
again. Behavior is like a local variable inside a code chunk, but here
counter is a class member variable, anyone can shed some light?
thanks
What you saw is expected, Why should member counter be modified by a
local Object() in any way?
Next time, please reproduce a basic reconstruction of the Object
class, since the order of its member declarations can affect the
inititialization list. Its also a pain to 'assume' what id might be.