c++ - Where is the destructor called? -


i'm learning c++ , want use objects in classes. output of program confuses me, because expected, data destructor called 2 times. object created "data data(3);" , it's destructor should called @ end of code block , when rects destructor called, destructor of data inside rect should called too. expected prints "data destructor" 2 times after code block ends. prints it, after data object created. why happen , how can delete allocated memory inside of data correctly?

class data { private:     int* data;     int size; public:     data() {         size = 10;         data = new int[size];     }     data(int size)         : size(size) {         data = new int[size];     }     virtual ~data() {         // delete data;         std::cout << "data destruktor" << std::endl;     }     void init(int val) {         (int = 0; < size; i++)             data[i] = val;     }     int& operator[](int index) {         return data[index];     }     int getsize() const {         return size;     } };  class rect { private:     data data;     int width, height; public:     rect() {}     rect(int width, int height, data data, int val = 0)         : width(width), height(height), data(data) {         data.init(val);     }     int getwidth() const {         return width;     }     int getheight() const {         return height;     }     int getarea() const {         return width * height;     }     data& getdata() {         return data;     } };  int main() {      {         data data(3);         std::cout << "data created" << std::endl;         rect rect(5, 4, data, 9);         std::cout << "end of code block" << std::endl;     }      std::cout << "end of program" << std::endl;      system("pause");     return 0; } 

output:

data created data destruktor end of code block data destruktor data destruktor end of program 

that because passing c'tor of rect copy of data, destroyed after constructor call , desctructor call.


Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -