Reputation: 149
I was messing around with a class and the constructor and destructor but now i'm not sure what is going on and hopefully someone here can explain why this is happening.
I have a piece of code as follows:
Animal dog1 = Animal("Thor");
Animal *pDog2 = &Animal("Loki");
Animal *pDog3 = new Animal("New");
The class just has a constructor that prints that the constructor and/or destructor is being invoked with the name of the Animal. What i see in the output, however, is that pDog2 is being created but right after that it is being destroyed. I have no idea why since it is not going out of scope yet, right?
The output given is:
Constructor of Thor called. Constructor of Loki called. Destructor of Loki called. Constructor of New called.
Hopefully someone can help me explain this.
Upvotes: 1
Views: 241
Reputation: 17483
Animal *pDog2 = &Animal("Loki");
What happens here is:
Animal
is created: Animal("Loki")
. The output "Constructor of Loki called." is shown.pDog2
.Animal *pDog2 = &Animal("Loki");
and the output "Destructor of Loki called." is shown.After that pDog2
becomes a dangling pointer as the temporary it pointed to doesn't exist anymore.
Upvotes: 3