what is the problem when object is created in below fashion

#include <stdio.h>

class xyz {

int mx;

public:

xyz::xyz(int inputx)

{printf("constructor for %d\n", inputx); mx=inputx;}

xyz::~xyz()

{printf("destructor of %d\n",mx);}

};

int main()

{

xyz abc(1); // right way of calling Lockable

printf("i ma here after abc(1).... \n");

xyz(2); // incorrect way of calling Lockable

printf ("I am here after just xyz(2)\n");

return 0;

}

Result :

constructor for 1

i ma here after abc(1)....

constructor for 2

destructor of 2

I am here after just xyz(2)

destructor of 1

Question -
When object is created like xyz(2), then why destructor is called immediately after constructor?
When object is created like xyz(2), then why destructor is called immediately after constructor?
No variable associate with this object hence it has practically no life time. Normally such an object is silently removed by the compiler, but since there might be something relevant in the constructor/destructor they're called nonetheless
thanks coder777. what do mean by 'No variable associate with this object'?
xyz(2); This will create an object without a name that will only exist on that line. That is why the constructor and destructor runs on that line.
thanks peter
Also one strange thing is that if the same program is run on solris then it yields different result.

Linux result-

constructor for 1

i ma here after abc(1)....

constructor for 2

destructor of 2

I am here after just xyz(2)

destructor of 1





Solaris result -

constructor for 1

i ma here after abc(1)....

constructor for 2

I am here after just xyz(2)

destructor of 2

destructor of 1

so confused :(
What compiler do you use. I would not expect it to compile with xyz:: before the constructor and destructor definitions.

If you fix that I would not expect the result you get on Solaris.
Topic archived. No new replies allowed.