Question: ```
#include<iostream>
using namespace std;

class Animal
{
    private:
        string name;
    public:
        Animal()
        {
            cout << "Animal created" << endl;
        }

        Animal(const Animal& other):
            name(other.name){
                cout << "Animal created by copying" << endl;
        }

        ~Animal()
        {
            cout << "Animal destroyed" << endl;
        }

        void setName(string name)
        {
            this->name = name;
        }
        void speak()const{
            cout << "My name is: " << name << endl;
    }
};

Animal createAnimal()
{
    Animal a;
    a.setName("Bertia");
    return a;
}

int main()
{

    Animal a_= createAnimal();
    a_.speak();

    return 0;
}

```

I got the output:

```
Animal created                                                         
My name is: Bertia
Animal destroyed

```

The "Animal created" constructor called here is for which object a or a\_ and also for destructor . Is it for called where we define Animal a or when
we call createAnimal() for a\_ And same goes for destructor , when does it get called after the end of main function for a\_ or after the end of createAnimal() function for a ?

Answer: 
> 
> Now my question is the "Animal created" for constructor is for which object a or a\_ and also the destructor is for which object a or a\_ ?
> 
> 
> 

Both. There is no need for two objects here.

> 
> And also please explain the procedure how the object here gets created and also the mechanism of copy constructor is applicable i.e. how the object is called and destroyed. 
> 
> 
> 

The object is created in `createAnimal` and returned to `main`, where it becomes `a_`. No copy construction is needed because it can be elided by extending the lifetime of the temporary.

The C++ standard specifically permits this optimization, one of the rare cases where optimizations are permitted that change the behavior of correct code.
You could add more couts to find out. E.g. something like this:

```
Animal createAnimal()
{
    std::cout << " creation of a " << std::endl;
    Animal a;
    a.setName("Bertia");
    std::cout << " returning from createAnimal " << std::endl;
    return a;        
}

int main()
{
   std::cout << " calling createAnimal() " << std::endl; 
   Animal a_= createAnimal();
   std::cout << " calling a_.speak() " << std::endl;
   a_.speak();
   std::cout << " returning from main " << std::endl;
   return 0;

```

}