Classes
Contents
Memory considerations for class objects
If we create an object dynamically we must delete it once we are done with it otherwise we introduce a leak.File: mem1.cpp
#include <iostream> #include <memory> using namespace std ; class Demo { public: int x1 ; int x2 ; Demo(int x1P , int x2P ) { x1 = x1P ; x2 = x2P ; //x1 = 5 ; //x2 = 10 ; cout << "Inside the constructor. " << endl ; } ~Demo() { cout << "Inside the destructor. " << endl ; } }; int main() { cout << "Before creating the object." << endl ; //Creating the object Demo* demo1Obj = new Demo( 5,6) ; delete ( demo1Obj ) ; cout << "End of main -----" << endl ; }If we assign an address of an existing object to a pointer variable and that object is on a stack then we should not delete it manually. A stack object is deleted by the compiler once it goes out of scope.
File: mem2.cpp
#include <iostream> #include <memory> using namespace std ; class Demo { public: int x1 ; int x2 ; Demo(int x1P , int x2P ) { x1 = x1P ; x2 = x2P ; //x1 = 5 ; //x2 = 10 ; cout << "Inside the constructor. " << endl ; } ~Demo() { cout << "Inside the destructor. " << endl ; } }; int main() { cout << "Before creating the object." << endl ; Demo demo1Object( 5,6) ; //Creating the object Demo* demo2ObjPtr = &demo1Object ; delete ( demo2ObjPtr ) ; cout << "End of main -----" << endl ; } $ g++ mem2.cpp ; ./a.exe mem2.cpp: In function ‘int main()’: mem2.cpp:33:24: warning: ‘void operator delete(void*, std::size_t)’ called on unallocated object ‘demo1Object’ [-Wfree-nonheap-object] 33 | delete ( demo2ObjPtr ) ; | ^ mem2.cpp:30:8: note: declared here 30 | Demo demo1Object( 5,6) ; | ^~~~~~~~~~~ Before creating the object. Inside the constructor. Inside the destructor. Aborted (core dumped)We have to be careful not to destroy an object twice that was created on the heap as that will also result in an error.
File: mem3.cpp
#include <iostream> #include <memory> using namespace std ; class Demo { public: int x1 ; int x2 ; Demo(int x1P , int x2P ) { x1 = x1P ; x2 = x2P ; //x1 = 5 ; //x2 = 10 ; cout << "Inside the constructor. " << endl ; } ~Demo() { cout << "Inside the destructor. " << endl ; } }; int main() { cout << "Before creating the object." << endl ; Demo* demo2ObjPtr = new Demo( 4, 6 ) ; delete ( demo2ObjPtr ) ; delete ( demo2ObjPtr ) ; cout << "End of main -----" << endl ; } $ g++ mem3.cpp ; ./a.exe Before creating the object. Inside the constructor. Inside the destructor. Inside the destructor. Aborted (core dumped)
Exercise
Create an array 2 of mystring objects with the values "Marvin" and "Hagler" .
Create an array of 2 mystring objects dynamically using the new operator with the no argument constructor.