Static Memory Management limitations Dynamic Memory Management Mechanism

  • Slides: 80
Download presentation
Static Memory Management, limitations, Dynamic Memory Management Mechanism, use of new and delete operators,

Static Memory Management, limitations, Dynamic Memory Management Mechanism, use of new and delete operators, Methods for allocating and deallocating memory for single objects and array of objects, use of set_new_handler function to slide 25 specify our own handler www. bookspar. com | Website for students | VTU NOTES

Memory for Program variables get allocated and deallocated during the runtime only. Eg –

Memory for Program variables get allocated and deallocated during the runtime only. Eg – we write int x; in some function of the code. When the code containing this line is compiled and linked, an executable file is generated. When executable file is executed, all instructions contained inside It, including ones to allocate memory for x are executed. Hence memory gets allocated for ‘x’ during runtime. This is known as Static Memory Allocation( although memory gets allocated during runtime only. ) www. bookspar. com | Website for students | VTU NOTES

The compiler writes instructions in the executable to De-allocate the memory previously allocated for

The compiler writes instructions in the executable to De-allocate the memory previously allocated for ‘x’ when it encounters the end of the function in which ‘x’ was declared in the source code. When the executable file is executed, all instructions inside it including the ones to deallocate memory for ‘x’ are executed. Hence the memory for ‘x’ gets deallocated during runtime. This is known as Static Memory Allocation Static Allocation and deallocation of memory has limitations: www. bookspar. com | Website for students | VTU NOTES

§ It is rigid § The programmers are forced to predict the total amount

§ It is rigid § The programmers are forced to predict the total amount of data the memory will utilize. § They write statements to declare precalculated amounts of Memory § During runtime, if more memory is required, static memory allocation cant fulfill the need. www. bookspar. com | Website for students | VTU NOTES

As in SM allocation and deallocation, in DM allocation and deallocation also, memory gets

As in SM allocation and deallocation, in DM allocation and deallocation also, memory gets allocated and deallocated during Runtime. However the decisions to do so is taken dynamically in response to the requirements arising during runtime itself. If the program is running and user indicates the need to feed in more data, a memory block sufficient to hold additional amount of data is immediately allocated. For this code, using relevant functions and operators provided by C & C++ has to be explicitly written in source www. bookspar. com | Website for students | VTU code. NOTES

Again, once a certain block of memory is no longer Needed, it can be

Again, once a certain block of memory is no longer Needed, it can be returned to OS. For this again, code using the relevant functions and Operators provided by C & C++ has to be explicitly written in the source code www. bookspar. com | Website for students | VTU NOTES

//dynamic. cpp //new operator, keyword takes a #include <iostream. h> // predefined datatype as

//dynamic. cpp //new operator, keyword takes a #include <iostream. h> // predefined datatype as operand( int) void main() //new allocates memory to hold 1 value of { int *iptr; //datatype i. e. passed as a parameter to it in iptr = new int; // heap( 4 bytes). Finally it returns the address *iptr=10; //of the allocated block. The allocated block cout << *iptr << endl; // can then be accessed through the } //pointer www. bookspar. com | Website for students | VTU NOTES

Statement: int *iptr; 1265 xxxx Four bytes get allocated for iptr containing junk value

Statement: int *iptr; 1265 xxxx Four bytes get allocated for iptr containing junk value with adrresses from 1265 to 1268(say) Figure for Dynamic Memory Allocation iptr www. bookspar. com | Website for students | VTU NOTES

Statement: iptr = new int; 1265 5972 xxxx 4 bytes iptr The new operator

Statement: iptr = new int; 1265 5972 xxxx 4 bytes iptr The new operator allocates memory in the heap to hold 1 integer type value. Suppose block from byte with address 5972 to byte with address 5975 get allocated. The new operator returns the base address of block (5972). This value gets stored in iptr. | Website for students | VTU www. bookspar. com NOTES

1265 5972 10 iptr fig - Dynamic Memory Allocation iptr is dereferenced and value

1265 5972 10 iptr fig - Dynamic Memory Allocation iptr is dereferenced and value 10 gets written into the memory Block of 4 bytes at which iptr points( 5972 to 5975). www. bookspar. com | Website for students | VTU NOTES

Statement : cout << *iptr << endl; 1265 5972 10 iptr is again dereferenced

Statement : cout << *iptr << endl; 1265 5972 10 iptr is again dereferenced and value 10 gets written into the memory block of 4 bytes to which iptr points (5972 to 5975) is read. www. bookspar. com | Website for students | VTU NOTES

The new operator can be used to create multiple blocks of memory also shown

The new operator can be used to create multiple blocks of memory also shown in dynarray. cpp www. bookspar. com | Website for students | VTU NOTES

The Set_new_handler() function – New operator attempts to capture more chunks of memory from

The Set_new_handler() function – New operator attempts to capture more chunks of memory from heap during run-time. If there is no memory available to satisfy this attempt, we get out of memory condition. new operator when faced with out-of-memory condition, calls a global function -> new_handler function, then throws an exception bad_alloc. We can specify our own new handler() function also. www. bookspar. com | Website for students | VTU NOTES

We can specify that the New operator upon encountering out-of-memory-condition, calls a function of

We can specify that the New operator upon encountering out-of-memory-condition, calls a function of our choice. This is done by calling ‘set_new_handler() fn and passing the name of function desired as a parameter to it. Prototype of set_new_handler is found in new. h header file. New_handler set_new_handler(new_handler); New_handler is a datatype and a function pointer Type. www. bookspar. com | Website for students | VTU NOTES

The formal argument of the set_new_handler() function is a function pointer. If we pass

The formal argument of the set_new_handler() function is a function pointer. If we pass name of our desired function as a parameter to set_new_handler() function, all subsequent out-of-memory conditions cause new operator to call it and our desired function becomes new_handler. When set_new_handler() is called , it returns a pointer to the previous new handler function Illustrative example new_handler. cpp Code for specifying a new_handler function www. bookspar. com | Website for students | VTU NOTES

If os is unable to allocate the requested amount of memory, from given code,

If os is unable to allocate the requested amount of memory, from given code, new operator fails. new_handler function is called. The call to set_new_handler() before the call to new operator , has already set function my. New. Handler as new handler. Important Characteristic of new operator – When its request for memory fails, it calls new handler function repeatedly until the request is satisfied. We can make new_handler function log an error message and then call the abort() function. www. bookspar. com | Website for students | VTU NOTES

Void my. New. Handler() { //statement to log a suitable error message Abort(); }

Void my. New. Handler() { //statement to log a suitable error message Abort(); } Another action – Replace the existing new handler by another one i. e. call the set_new_handler() from within the existing new handler and pass name of new handler as a parameter to it. www. bookspar. com | Website for students | VTU NOTES

#include <new. h> void main() { //make an attempt to resolve out of memory

#include <new. h> void main() { //make an attempt to resolve out of memory condition If (above_attempt_fails) set_new_handler(my. Another. Newhandler); } Best way to define new handler is to allocate some buffer in advance and free it part by part when the need arises. www. bookspar. com | Website for students | VTU NOTES

§ A constructor gets called automatically for each object that has just got created.

§ A constructor gets called automatically for each object that has just got created. § Appears as member function of each class whether It is defined or not. § Has same name as that of the class and doesn’t return anything (not even void ) Constructor Prototype <class name> (<parameter list>); § Constructor fulfills the need to guarantee the data initialization. www. bookspar. com | Website for students | VTU NOTES

§ Domain constraints on the values of data Members can also be implemented via

§ Domain constraints on the values of data Members can also be implemented via constructors. Eg- We want value of all data member f. Inches of each object of class Distance to be between 0. 0 and 12. 0 at all times within the lifetime of object. But this condition get violated in case of an object just created. However introducing a suitable constructor to the class Distance can enforce this condition. The compiler emdeds a call to the constructor for each object when it is created. Suppose a class A has been declared as follows. www. bookspar. com | Website for students | VTU NOTES

/*A. h*/ Class A { Int x; Public: void setx(const int = 0); int

/*A. h*/ Class A { Int x; Public: void setx(const int = 0); int getx(); }; www. bookspar. com | Website for students | VTU NOTES

/*Amain. cpp*/ Void main() { A A 1; //object declared … constructor called }

/*Amain. cpp*/ Void main() { A A 1; //object declared … constructor called } Code for constructor getting called automatically for an object when it is created. www. bookspar. com | Website for students | VTU NOTES

Statement in main() is transformed into Following statements A A 1; //memory allocated for

Statement in main() is transformed into Following statements A A 1; //memory allocated for object (4 bytes) A 1. A //constructor called implicitly by compiler Second statement is transformed to A(&A 1); -> C calls that object of class A passed as parameter for this pointer. C++compiler after ensuring that none of nonmfs are accessing private data of the class A, it converts C++ code to C code. www. bookspar. com | Website for students | VTU NOTES

A *Aptr; Aptr = new A; // constrcutor called implicitly //by compiler The second

A *Aptr; Aptr = new A; // constrcutor called implicitly //by compiler The second statement is converted into a sequence of 2 statements Aptr = new A; Aptr -> A(); // constructor called implicitly by compiler. A(Aptr); //see chapter 2 Constructors don’t allocate memory for objects. They are mfs called for each object immediately after memory has been allocated for the object. www. bookspar. com | Website for students | VTU NOTES

class String { //character pointer to point at the char *c. Str; //character array

class String { //character pointer to point at the char *c. Str; //character array long unsigned int len; // to hold length of //character array /*rest of the class string*/ }; www. bookspar. com | Website for students | VTU NOTES

101 27 cstr 101 len a b c � 3 s 1 Fig- Memory

101 27 cstr 101 len a b c 3 s 1 Fig- Memory layout of an object of class String www. bookspar. com | Website for students | VTU NOTES

Constructors take arguments and can hence be overloaded by 1. Passing initial values for

Constructors take arguments and can hence be overloaded by 1. Passing initial values for the data members contained in the object of a particular class www. bookspar. com | Website for students | VTU NOTES

Eg – The Distance class in a C++ program can also be overloaded by

Eg – The Distance class in a C++ program can also be overloaded by passing initial values for data Members i. Feet & f. Inches as follows in class Distance and member function definition. /*distance. h*/ class Distance { public: Distance(); Distance(int, float); //prototype of parameterized //constructor /*rest of class Distance }; www. bookspar. com | Website for students | VTU NOTES

/* beginning of distance. cpp*/ #include “Distance. h” Distance: : Distance() { i. Feet

/* beginning of distance. cpp*/ #include “Distance. h” Distance: : Distance() { i. Feet = 0; f. Inches=0. 0; } www. bookspar. com | Website for students | VTU NOTES

Distance : : Distance( int p, float q) { i. Feet = p; set.

Distance : : Distance( int p, float q) { i. Feet = p; set. Inches(q); } /*definitions of the rest of the functiions of class Distance*/ www. bookspar. com | Website for students | VTU NOTES

/*dist. Test 1. cpp*/ #include <iostream. h> #include “Distance. h” void main() { Distance

/*dist. Test 1. cpp*/ #include <iostream. h> #include “Distance. h” void main() { Distance d 1(1, 1. 1); //parameterized constructor //called cout << “d 1. get. Feet() << “ “ << d 1. get. Inches(); } Listing shows A user defined parameterized Constructor called by creating an object in the Stack O/P – 1 1. 1 SLIDE-A www. bookspar. com | Website for students | VTU NOTES

/*dist. Test 2. cpp*/ #include <iostream. h> #include “Distance. h” void main() { Distance

/*dist. Test 2. cpp*/ #include <iostream. h> #include “Distance. h” void main() { Distance *dptr; dptr = new Distance(1, 1. 1); //parameterized constructor //called cout << “dptr->get. Feet() << “ “ << dptr->get. Inches(); } Listing shows A user defined parameterized constructor – called by creating an object in the heap. O/P 1 1. 1 SLIDE-B www. bookspar. com | Website for students | VTU NOTES

First line of main() in Slide-A and second line Of main() in slide-B show

First line of main() in Slide-A and second line Of main() in slide-B show the syntax for passing values to the parameterized constructor Parameterized constructor is prototyped and defined like any other member function but it doesn’t return any value. www. bookspar. com | Website for students | VTU NOTES

§ Then the following statement will not compile Distance d 1; //Error no matching

§ Then the following statement will not compile Distance d 1; //Error no matching constructor The formal arguments of the parameterized constructor can be assigned default values as in other member functions. Here default constructor function should be provided, else an ambiguity error arise www. bookspar. com | Website for students | VTU NOTES

The formal arguments of the parameterized constructor can be assigned default values as in

The formal arguments of the parameterized constructor can be assigned default values as in other member functions. Here default constructor function should be provided, else an ambiguity error arise when we attempt to create an object without passing any values to the constructor www. bookspar. com | Website for students | VTU NOTES

class Distance { public: //Distance(); //zero argument constructor //commented out Distance(int = 0, float=0.

class Distance { public: //Distance(); //zero argument constructor //commented out Distance(int = 0, float=0. 0); //default values //given /*rest of the class Distance*/ Listing – Default values given to parameters of a parameterized constructor make zero argument constructor unnecessary www. bookspar. com | Website for students | VTU NOTES

If we write , Distance d 1; An ambiguity error arises if zero argument

If we write , Distance d 1; An ambiguity error arises if zero argument constructor is also defined. Reason – Both Parameterized and default constructor can resolve this statement. www. bookspar. com | Website for students | VTU NOTES

Lets create a parameterized constructor for the class string and assign default value for

Lets create a parameterized constructor for the class string and assign default value for the argument of the parameterized constructor. The constructor would handle the following statements. String s 1(“abc”); or char *c. Ptr=“abc” String s 1(cptr); or char Arr[10] = “abc”; String s 1(c. Arr); In each of these statements, we are passing the base address of the memory block in which the string itself is stored to the constructor www. bookspar. com | Website for students | VTU NOTES

www. bookspar. com | Website for students | VTU NOTES

www. bookspar. com | Website for students | VTU NOTES

p is a formal argument of the constructor. The address of the memory block

p is a formal argument of the constructor. The address of the memory block containing the passed string is 50. This address 50 is passed to the constructor. Hence value of p = 50. But constructor should execute in such a manner that a different block i. e. long to hold the string at which p is pointing should also be allocated dynamically in heap area that extends from 101 to 104. The base address of this block of memory is stored in pointer embedded in s 1. The string is copied from the memory block at which p points to memory block at which s 1. c. Str points. Finally s. len is appropriately set to 3. www. bookspar. com | Website for students | VTU NOTES

50 50 A 27 c. Str len s 1 101 3 b A c

50 50 A 27 c. Str len s 1 101 3 b A c b c Assigning a string to an object of class String www. bookspar. com | Website for students | VTU NOTES

The value of c. Ptr is passed as a parameter to the constructor. This

The value of c. Ptr is passed as a parameter to the constructor. This value is stored in p. Hence p & c. Ptr points to the same place. s 1. c. Str should be made to point at a base address of a different memory block of 4 bytes that has been exclusively allocated for the purpose. Only the contents of memory block whose base address is passed to the constructor should be copied into memory block at which s 1. c. Str points. www. bookspar. com | Website for students | VTU NOTES

c. Ptr 50 A 50 50 p 27 c. Str len 101 b A

c. Ptr 50 A 50 50 p 27 c. Str len 101 b A c b c 101 3 Assigning a string to an object of class String www. bookspar. com | Website for students | VTU NOTES

c. Arr 50 50 Fig -p. Assigning a string the class String 50 a

c. Arr 50 50 Fig -p. Assigning a string the class String 50 a to an b object c of 27 c. Str len s 1 101 3 a b c 101 www. bookspar. com | Website for students | VTU NOTES

is very similar to II case. Here we are passing the name of the

is very similar to II case. Here we are passing the name of the array. But name of the array is itself is a fixed pointer that contains the address Of the memory block containing actual address of array i. e. seen in diagram. The formal argument of the constructor should be as follows : const char *const 1. It should be a constant pointer because throughout the execution of the constructor, it should continue to point to the same memory block. www. bookspar. com | Website for students | VTU NOTES

2. It should be a pointer to a constant because even inadvertently, the library

2. It should be a pointer to a constant because even inadvertently, the library programmer should not dereference it to change the contents of the memory block at which it is pointing. 3. Specify a default value for ‘p’(NULL) so that there is no need to seperately define a zero default Constructor Definition of class String along with prototype of the constructor and its definition are as follows www. bookspar. com | Website for students | VTU NOTES

Class String { char *c. Str; long unsigned int len; public: //Default constructor*/ String(const

Class String { char *c. Str; long unsigned int len; public: //Default constructor*/ String(const char *const p = NULL); const char *get. String(); /*rest of the class String*/ }; www. bookspar. com | Website for students | VTU NOTES

String: : String(const char* const p) { if (p==NULL) { c. Str=NULL; len =

String: : String(const char* const p) { if (p==NULL) { c. Str=NULL; len = 0; } else { len = strlen(p); // dynamically allocate a seperate c. Str=new char[len+1]; //memory block & copy into it strcpy(c. Str, p); } www. bookspar. com | Website for students | VTU NOTES

Const char *string: : get. String() { return c. Str; } /*string. cpp*/ void

Const char *string: : get. String() { return c. Str; } /*string. cpp*/ void main() { String s 1(“abc”); //pass a string to parameterized //constructor display the string Cout << s 1. get. String() << endl; } user-defined parameterized constructor for acquiring memory outside the object www. bookspar. com | Website for students | VTU NOTES

Another function called getstring is written in class String that enables to display the

Another function called getstring is written in class String that enables to display the string itself and returns a const char* so that only pointer to a constant can be equated to a call to this function const char* p = s 1. getstring(); www. bookspar. com | Website for students | VTU NOTES

§ It is called when object is created and equated to an existing object

§ It is called when object is created and equated to an existing object at the same time. § The copy constructor is called for an object being created. § The preexisting object is passed as parameter to it into the object for which it is called. www. bookspar. com | Website for students | VTU NOTES

If we don’t define the copy constructor for the class, the compiler defines it

If we don’t define the copy constructor for the class, the compiler defines it for us. In either case, a call is embedded to it under 3 circumstances. 1. When an object is created an simultaneously equated to another existing object, the copy constructor is called for the object for object being created. The object to which this object was equated is passed as parameter to the constructor. www. bookspar. com | Website for students | VTU NOTES

A A 1 //default constructor called A A 2=A 1; //copy constructor called Or

A A 1 //default constructor called A A 2=A 1; //copy constructor called Or A A 2(A 1); //copy constructor called Or A *APtr = new A(A 1) //copy constructor called Here copy constructor is called for A 2 and for APtr while A 1 is passed as parameter to the copy constructor in both cases. www. bookspar. com | Website for students | VTU NOTES

formal argument of a function. The copy constructor is called for the argument object.

formal argument of a function. The copy constructor is called for the argument object. The object passed as parameter to the function is passed as parameter to the constructor. void abc(A); A A 1; //default constructor called abc(A 1) // copy constructor called Void abc( A A 2) { /* definition of abc() Here again copy constructor is called for A 2, while A 1 is passed as a parameter to the constructor } www. bookspar. com | Website for students | VTU NOTES

A abc() { A A 1; //default constructor called //remaining part of definition of

A abc() { A A 1; //default constructor called //remaining part of definition of abc() Return A 1; } A A 2 = abc(); //copy constructor called Once more, copy constructor is called for A 2 while A 1 is passed as a parameter to the copy constrcutor www. bookspar. com | Website for students | VTU NOTES

Class A { public: A(A&); //default copy constructor } A: : A(A& AObj) //default

Class A { public: A(A&); //default copy constructor } A: : A(A& AObj) //default copy constructor { *this=AObj; //copies the passed object //into the invoking object. } www. bookspar. com | Website for students | VTU NOTES

§ Is converted as follows A A 2; //memory allocated A: : A(A& AObj)

§ Is converted as follows A A 2; //memory allocated A: : A(A& AObj) //default copy constructor A 2. A(A 1) //copy constructor called for A 2 and A 1 //is passed as parameter to it This last statement is transformed to A(&A 2, A 1) //see this pointer in chapter 2 When above statement executes, ‘AObj’ (formal arg in copy constructor becomes a reference to ‘A 1’ whereas this pointer points at A 2 the invoking object). www. bookspar. com | Website for students | VTU NOTES

§ Suppose formal argument (AObj) of cc is not reference and following statement executes

§ Suppose formal argument (AObj) of cc is not reference and following statement executes A A 2 = A 1; CC will be called for A 2 and A 1 will be passed as parameter to it. Reason – AObj is a nonreference formal arg of constructor & an endless chain of calls to cc will be initiated. c. c->copy constructor www. bookspar. com | Website for students | VTU NOTES

§ However if formal arg of cc is a reference, no constructor will be

§ However if formal arg of cc is a reference, no constructor will be called for it. This is because reference to an object is not a seperate object and no memory is allocated. § Hence a call to constructor is not embedded for it. www. bookspar. com | Website for students | VTU NOTES

§ Recollect the conditions we decided to implement for all objects of class String.

§ Recollect the conditions we decided to implement for all objects of class String. § Suppose an object of class String is created and at same time equated to another object of the class. Eg – String(“abc”); String s 2=s 1; //cc is called for s 2 and //s 1 passed as a parameter to it. www. bookspar. com | Website for students | VTU NOTES

§ To overcome this problem of default cc , we define our own cc.

§ To overcome this problem of default cc , we define our own cc. § From within cc of a class String, a separate memory block must be allocated dynamically in heap. This memory must be equal in length to that of string at which pointer of object passed as parameter (s 1) points. string. cpp www. bookspar. com | Website for students | VTU NOTES

Class String { char *c. Str; long unsigned int len; Public: String(const String &);

Class String { char *c. Str; long unsigned int len; Public: String(const String &); //rest of class String }; www. bookspar. com | Website for students | VTU NOTES

String: : String(const String& ss) { if(ss. c. Str == NULL) //if passed object’s

String: : String(const String& ss) { if(ss. c. Str == NULL) //if passed object’s { //pointer is NULL c. Str = NULL; len=0; } else { len = strlen(ss. len); c. Str = new char[len+1]; strcpy(c. Str, ss. c. Str); } } www. bookspar. com | Website for students | VTU NOTES

Void main() { String s 1(“abc”); String s 2=s 1; cout << s 1.

Void main() { String s 1(“abc”); String s 2=s 1; cout << s 1. getstring() << endl; } www. bookspar. com | Website for students | VTU NOTES

§ Here in cc , formal arg is a constant that has to be

§ Here in cc , formal arg is a constant that has to be a reference in order to prevent an endless chain of calls to itself. LP want to prevent change in value of object that get passed to the constructor www. bookspar. com | Website for students | VTU NOTES

§ The prototype of a destructor ~<class Name>(); Need for Destructor – guarantees deinitialization

§ The prototype of a destructor ~<class Name>(); Need for Destructor – guarantees deinitialization of member data of a class and frees up the resources acquired by the object during lifetime. Compiler embeds a call to destructor for every object when it is destroyed. Void main(){ A A 1; } //A 1 goes out of scope here A 1 goes out of scope before main() fn terminates. www. bookspar. com | Website for students | VTU NOTES

§ Compiler embeds a call to destructor for A 1. It embeds the following

§ Compiler embeds a call to destructor for A 1. It embeds the following statement. A 1. ~A(); //see chapter 2 An explicit call to destructor for an existing object is forbidden. Above statement can be transformed into ~A(&A 1); //see chapter 2 Destructor will also be called for an object that has been dynamically created in heap before the delete operator is applied on the pointer pointing at it. www. bookspar. com | Website for students | VTU NOTES

A *APtr; APtr = new A; //Object created – constructor //called … … delete

A *APtr; APtr = new A; //Object created – constructor //called … … delete APtr; //Object destroyed – destructor //called Last statement is transformed into APtr -> ~A(); //destructor called for //APtr delete APtr; //memory for *APtr //released. www. bookspar. com | Website for students | VTU NOTES

1. Destructor is called for object i. e. going out of Scope. Memory occupied

1. Destructor is called for object i. e. going out of Scope. Memory occupied by object itself is deallocated. 2. Delete APtr; Is transformed into ~A(APtr); //on this pointer Destructor is a member function that is called for each object just before the object goes out of scope (gets destroyed) 1. Compiler embeds a call to destructor for each & every object i. e. going out of scope( gets destroyed) www. bookspar. com | Website for students | VTU NOTES

Before Class A {… … Public: …. . … //no destructor }; After class

Before Class A {… … Public: …. . … //no destructor }; After class A {… public: //implicitly by compiler ~A(); //prototype inserted //implicitly by compiler … }; www. bookspar. com | Website for students | VTU NOTES

A: : ~A() { //empty function definition inserted implicitly by //compiler … … }

A: : ~A() { //empty function definition inserted implicitly by //compiler … … } www. bookspar. com | Website for students | VTU NOTES

Lets add our own destructor to class A defined In previous slide and verify

Lets add our own destructor to class A defined In previous slide and verify whether destructor is Actually called Implicitly by compiler or not. //A. h class A { int x; public: A(); void setx(const int =0); int getx(); ~A(); //our own destructor }; www. bookspar. com | Website for students | VTU NOTES

/*A. cpp #include “A. h” A: : A() { cout << “Constructor function of

/*A. cpp #include “A. h” A: : A() { cout << “Constructor function of class A calledn”; } A: : ~A() { Cout << “Destructor function of class A calledn”; } www. bookspar. com | Website for students | VTU NOTES

#include <iostream. h> void main() { A A 1; Cout << “End of Program”;

#include <iostream. h> void main() { A A 1; Cout << “End of Program”; } o/p – Constructor of class A called End of program Destructor of class A called www. bookspar. com | Website for students | VTU NOTES

§ Eg – consider the following code block { … String S 1(“abc”); ….

§ Eg – consider the following code block { … String S 1(“abc”); …. . } www. bookspar. com | Website for students | VTU NOTES

§ The memory allocated to S 1 gets deallocated when this block finishes execution

§ The memory allocated to S 1 gets deallocated when this block finishes execution § But s 1. c. Str was pointing at a memory block that was dynamically allocated in the heap area. § After S 1 gets destroyed, this memory block remains as locked up lost resource and s 1. c. Str is no longer available. This is memory Leak. § User defined destructor String: : ~String() //our own destructor { if (c. Str!=NULL) //if memory exists delete [ ] c. Str; //destroy it } www. bookspar. com | Website for students | VTU NOTES

A: : A() { cout << “Constructor of the class A calledn”; } A:

A: : A() { cout << “Constructor of the class A calledn”; } A: : ~A() { //empty definition implicitly by compiler } Void main() { A A 1; Cout << “End of the Programn”; } www. bookspar. com | Website for students | VTU NOTES

such data type § Consider adding a function to class String Void String :

such data type § Consider adding a function to class String Void String : : add. Char(char); Function to add a character to a string S 1(“abc”); Pointer inside s 1 points at a memory block of 4 Bytes. Executing s 1. addchar(‘d’); www. bookspar. com | Website for students | VTU NOTES

§ Another block of 5 bytes should get allocated. § String contained in memory

§ Another block of 5 bytes should get allocated. § String contained in memory block at which s 1. c. Str is pointing should get copied into this new memory block. § Character d should get appended to string NULL character should get further appended to the string § s 1. str should be made to point to this new memory block. § The memory block at which s 1. c. Str was pointing previously should be deallocated to prevent memory leaks. www. bookspar. com | Website for students | VTU NOTES

§ There are no memory leaks( destructor frees up unwanted memory) § There are

§ There are no memory leaks( destructor frees up unwanted memory) § There are no runtime errors( no 2 calls to destructor try to free up same block of memory) § Data is never in an invalid state and domain constraints on values of data members are never violated. www. bookspar. com | Website for students | VTU NOTES