C++ dought completely Novice -


#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 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 output:

animal created                                                          name is: bertia animal destroyed 

the "animal created" constructor called here object or a_ , destructor . called define animal or when call createanimal() a_ , same goes destructor , when called after end of main function a_ or after end of createanimal() function ?

now question "animal created" constructor object or a_ , destructor object or a_ ?

both. there no need 2 objects here.

and please explain procedure how object here gets created , mechanism of copy constructor applicable i.e. how object called , destroyed.

the object created in createanimal , returned main, becomes a_. no copy construction needed because can elided extending lifetime of temporary.

the c++ standard permits optimization, 1 of rare cases optimizations permitted change behavior of correct code.


Comments

Popular posts from this blog

java - Date formats difference between yyyy-MM-dd'T'HH:mm:ss and yyyy-MM-dd'T'HH:mm:ssXXX -

c# - Get rid of xmlns attribute when adding node to existing xml -