Bob
Bob

Reputation: 149

C++ object creation and destruction

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

Answers (1)

Edgar Rokjān
Edgar Rokjān

Reputation: 17483

Animal *pDog2 = &Animal("Loki");

What happens here is:

  1. A temporary object of type Animal is created: Animal("Loki"). The output "Constructor of Loki called." is shown.
  2. The address of this temporary is assigned to pDog2.
  3. The temporary is destroyed at the end of the full expression: 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

Related Questions