Apr 23, 2012 at 7:10am UTC
#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?
Apr 23, 2012 at 9:27am UTC
thanks coder777. what do mean by 'No variable associate with this object'?
Apr 23, 2012 at 9:54am UTC
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.
Apr 23, 2012 at 11:17am UTC
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 :(
Apr 23, 2012 at 11:53am UTC
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.