-5

i new on c++ object oriented program. i look in c++, when i want to create new object i can make as a pointer

MyClass* myobject1 = new MyaClass();

and i must to delete explicit when i want to garbage the object from memory, like delete object.

My question, Assume inside myobject1 i created a new object pointer (ex. MyClass2 myobject2 = new MyCalss2()). When i delete myobject1, should i do explicity delete too myobject2 on deconstructor myobject1, or myobject2 automatic will garbage?

user4581301
  • 29,019
  • 5
  • 26
  • 45
heriono
  • 15
  • 1
  • 4
  • 3
    There is no garbage collection in C++. Every object constructed with `new` must be destroyed with `delete`, in order to avoid leaking memory. – Sam Varshavchik Oct 31 '17 at 01:46
  • 1
    `MyClass2 myobject2` is not a pointer. You cannot assign a pointer to it and there is no need to `delete` it. – user4581301 Oct 31 '17 at 01:46
  • 3
    Please post real code – M.M Oct 31 '17 at 01:46
  • 1
    Take a look [here](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-with-modern-c). – user0042 Oct 31 '17 at 01:50
  • 1
    [Why should C++ programmers minimize use of 'new'?](https://stackoverflow.com/questions/6500313/why-should-c-programmers-minimize-use-of-new?rq=1) – Bo Persson Oct 31 '17 at 06:22

2 Answers2

0

If you have allocated Dynamic memory,Open database connection or open a file,In C++ ,It is your duty to free the allocated memory,close database connections & close files.

If you use smart pointers for Dynamic memory allocation, you don't need to worry about freeing allocated memory .Smart pointers will free the allocated memory when they goes out of the scope.

In your Question,In MyClass object you have dynamically allocated memory for MyClass2 object.You have to write your own destructor for MyClass2 & it must be called MyClass destructor. If you haven't write proper destructor for MyClass2, when you call delete on myobject1, It will call MyClass destructor & inside default destructor of MyClass2 will be called & it will not free dynamically allocated memory.

https://www.linkedin.com/pulse/write-bu-gamindu-udayanga/?lipi=urn%3Ali%3Apage%3Ad_flagship3_profile_view_base_post_details%3BtIg1TW%2BKT7ugkY8Vs3s6Ng%3D%3D

0

You answered your question.

 "i must to delete explicit when i want to garbage the object from memory, like delete object."

There is no garbage collection in C++. If you create a new pointer you have to delete it to avoid memory leaks. You can also use helper classes such as auto_ptr, unique_ptr, shared_ptr etc according to the usage.