Destructors and Storage ClassesSlide 2Slide 3Slide 4Slide 5Slide 6Slide 7Slide 8Slide 9Slide 10Slide 11Slide 12Slide 13Slide 14Destructors – What are they?Destructors – When called?DestructorsDestructors and InheritanceDestructors and Inheritance with PointersCalling of Constructors and DestructorsConstructor and Destructor ExampleSlide 22Slide 23Tonight’s Lab & Homework AssignmentsCS1C – Advanced Programming in C++Saddleback College Fall 2011 – J TateyamaMemory Management and DestructorsTopic 8 – Shrinkwrap Chapter 6CS1C – Saddleback CollegeClass ReviewClass – defines the variables and methods common to objects of a given type. The class provides the blueprint or prototype for the objects. An object is an instance of a class. instance methodsinstance variablesInstantiate an object of type Rectangle (an instance of the class)class Rectangle{public: Rectangle( ); Rectangle(float l, float w); float GetLength( ) const; float GetWidth( ) const;private: float recLength; float recWidth;};void main( ){ Rectangle recOne;}CS1C – Saddleback College4 Categories of Memory in C++Code – Contains machine instructions for all function and member functionsStatic Data – Containing the following:• Global variables• Local variables or class data members that are declare with static modifierRun-time Stack – C++ variables not in the above are contained here; which means most of your variablesFree Store or Heap – area for memory explicitly requested using the new operatorCS1C – Saddleback CollegeCode MemoryContains machine instructions for all function and member functionsGenerally cannot change the values in this area of member once a function has been compiled. Function pointers – makes it possible to reference a value in this section of memory • The name of a function without ( ) denotes a function pointer• Use typedef to make function pointer types easier to readvoid print_table(double (*f)(double)) replace withtypedef double(*DoubleFuncPtr)(double);void print_table(DoubleFuncPtr f);CS1C – Saddleback CollegeStatic Data MemoryHolds global and static valuesGlobal variables• Defined outside the scope of any functions or classes• One important property for memory management• Within each name space, each name can be mapped one-to-one to an object • This is the opposite of a local variable which is created anew each time a function is executed • Each global variable can be assigned a fixed-size block of memory prior to execution• Global variables can be initialized by assignment or constructor before execution of main beginsCS1C – Saddleback CollegeStatic Data MemoryGlobal variable example: int counter = 0; int counting_func() { counter++ return counter; }CS1C – Saddleback CollegeStatic Data MemoryStatic variable – both local variables and data members can be declared static and is similar to a global variable: • Only has on value attached to the name• Is assigned memory once, initialized before main begins execution• Continues to exist until the end of executionCan rewrite the previous example as follows:int counting_func() { static int counter = 0; // Will be initialized only once counter++ return counter; }CS1C – Saddleback CollegeRun-time StackValues in the run-time stack are tied to function entry and exitFunction invocations execute in an orderly fashion, for example:• f invokes g• g invokes h • h must end before g will continue• g must end before f will resumeThis LIFO behavior allows stack memory to be managed efficientlyEach function has a block of memory on the stack called an activation record containing parameters, return address, local variables An internal pointer refers to the top of the run-time stackCS1C – Saddleback CollegeActivation Records on the StackCS1C – Saddleback CollegeStack DrawbacksWhile a stack is every efficient use of memory there are 2 major drawbacks of using the stack to store local variables• Lifetime • Stack-memory values is tied to function entry and exit• Once a function exits the values cease to exist • Any attempt to reference them after being deleted will cause an error.• Size• Must be known at compile time when the activation record is laid out.CS1C – Saddleback CollegeHeap MemoryMany situations where stack memory is inappropriate• Array size unknown• How many nodes needed in a linked list• Lifetime of the value isn't tied to procedure entry and exitFree store (or Heap) is the storage area for all values explicitly requested when using the “new” operatorMemory allocator finds storage location for the new object in the heapThe location of the object in memory is it's memory address – (dynamic memory allocation)Pointers are used to manipulate dynamically allocation values• Pointers themselves may exist on the stack or on the heapOnce done with dynamically allocated memory it must be returned to the free store using the “delete” operatorCS1C – Saddleback CollegeValues on the Stack and on the HeapAfter the following statement is executed then the Stack and Heap have the values shown belowEmployee* boss = new Employee(“Smart, Sally”, 150000);CS1C – Saddleback CollegeCommon Memory ErrorsIn C++, the programmer is responsible for memory managementPointers can refer to memory in any of the four memory categoriesSome of the possible errors that may occur include• Using a pointer that has not been initialized• Using a pointer to reference a memory location that is no longer valid• Forgetting to delete a dynamically allocation section of memory• Deleting a memory value that was never allocated• Deleting a dynamically allocated section of memory more than onceCS1C – Saddleback CollegeInitializer Lists – Additional Notes Must be used for the following:• Data fields declared as constant• References (like constants – assigned once and never modified)• Assigning size to a vectorclass PartDescription{public: PartDescription(string part_nm, int inventory_num);private: const string name; const int part_number; vector<PartDescription*> subcomponents;};PartDescription::PartDescription(string part_nm, int inventory_num) : name(part_nm), part_number(inventory_num), subcomponents(3){}CS1C – Saddleback CollegeDestructors – What are they?Basically the opposite of
View Full Document