Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore BCA122_OOPS(Draft 2)(1)

BCA122_OOPS(Draft 2)(1)

Published by Teamlease Edtech Ltd (Amita Chitroda), 2021-05-14 07:57:21

Description: BCA122_OOPS(Draft 2)(1)

Search

Read the Text Version

8.3THROWING AND EXCEPTION Exceptions can be thrown anywhere within a code block using throw statement. The operand of the throw statement determines a type for the exception and can be any expression and the type of the result of the expression determines the type of exception thrown. Following is an example of throwing an exception when dividing by zero condition occurs double division (int a, int b) { if (b == 0) { throw \"Division by zero condition!\"; } return (a/b); 8.4 CATCHING EXCEPTIONS The catch block following the try block catches any exception. You can specify what type of exception you want to catch and this is determined by the exception declaration that appears in parentheses following the keyword catch. try { // protected code } catch(ExceptionName e ) { // code to handle ExceptionName exception } Above code will catch an exception of ExceptionName type. If you want to specify that a 200 CU IDOL SELF LEARNING MATERIAL (SLM)

catch block should handle any type of exception that is thrown in a try block, you must put an ellipsis, ..., between the parentheses enclosing the exception declaration as follows − try { // protected code } catch(...) { // code to handle any exception } The following is an example, which throws a division by zero exception and we catch it in catch block. #include<iostream> usingnamespace std; double division(int a,int b){ 201 if( b ==0){ throw\"Division by zero condition!\"; } return(a/b); } int main (){ int x =50; int y =0; CU IDOL SELF LEARNING MATERIAL (SLM)

double z =0; try{ z = division(x, y); cout << z << endl; }catch(constchar* msg){ cerr << msg << endl; } return0; } Because we are raising an exception of type const char*, so while catching this exception, we have to use const char* in catch block. If we compile and run above code, this would produce the following result − Division by zero condition! 8.5 SUMMARY  The exception handling scheme described here is flexible enough to cope with most synchronous exceptional circumstances. Its semantics are independent of machine details and can be implemented in several ways optimized for different aspects. In particular, portable and run-time efficient implementations are both possible. The exception handling scheme presented here should make error handling easier and less error-prone.  The try statement allows you to define a block of code to be tested for errors while it 202 CU IDOL SELF LEARNING MATERIAL (SLM)

is being executed.  The throw keyword throws an exception when a problem is detected, which lets us create a custom error.  The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.  The try and catch keywords come in pairs:  throw − A program throws an exception when a problem shows up. This is done using a throw keyword. catch − A program catches an exception with an exception handler at the place in a program where you want to handle the problem. The catch keyword indicates the catching of an exception. try − A try block identifies a block of code for which particular exceptions will be activated. It's followed by one or more catch blocks  Exception handling is not strictly synonymous with error handling, because the implementation allows the passing of an exception whether or not an error actually occurred. You can use exception handlers for things other than handling errors. For example, you can transfer control back to the original caller of a function. You might use this if you wanted to process the Quit key in a program and transfer control back to the driver program when the user types Quit. To do this exception handlers could be used to throw an object back to the driver.  The exception handling scheme described here is flexible enough to cope with most synchronous exceptional circumstances. Its semantics are independent of machine details and can be implemented in several ways optimized for different aspects. In particular, portable and run-time efficient implementations are both possible. The exception handling scheme presented here should make error handling easier and less error-prone. 203 CU IDOL SELF LEARNING MATERIAL (SLM)

8.6KEY WORDS/ABBREVIATIONS  Throw: C++ keyword used to throw (initiate) an exception. See exception handling.  Translation limit: a limit on the size of a source program that a compiler will accept.  Translation unit: a source file presented to a compiler with an object file produced as a result.  True:C++ keyword used to specify a value for the bool type.  Exception : object thrown by a throw-statement and (potentially) caught by an exception handler associated by a try-block. 8.7 LEARNINGACTIVITY 1. Write a program to catch more than two exceptions. __________________________________________________________________________ __________________________________________________________________________ 2. Is the following code block legal? try { ... } Finally { 204 CU IDOL SELF LEARNING MATERIAL (SLM)

... }_________________________________________________________________________ __________________________________________________________________________ _ 8.8UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive Types Question 1. Create a class with member functions that throw exceptions. Within this class, make a nested class to use as an exception object. It takes a single char* as its argument; this represents a description string. Create a member function that throws this exception. (State this in the function’s exception specification.) Write a try block that calls this function and a catch clause that handles the exception by printing out its description string. 2. Prove to yourself that if you create an exception object on the heap and throw the pointer to that object, it will not be cleaned up. 3. Create a destructor that throws an exception, and write code to prove to yourself that this is a bad idea by showing that if a new exception is thrown before the handler for the existing one is reached, terminate( ) is called. 4. Prove to yourself that all exception objects (the ones that are thrown) are properly destroyed. 5. Track the creation and passing of an exception using a class with a constructor and copy-constructor that announce themselves and provide as much information as possible about how the object is being created (and in the case of the copy- constructor, what object it’s being created from). Set up an interesting situation, throw an object of your new type, and analyze the program. 205 CU IDOL SELF LEARNING MATERIAL (SLM)

B. Multiple Choice Questions 206 1. Which is used to handle the exceptions in C++? (a) catch handler (b) handler (c) exception handler (d) throw 2. Which type of program is recommended to include in try block? (a) static memory allocation (b) dynamic memory allocation (c) const reference (d) pointer 3. Which statement is used to catch all types of exceptions? (a) catch() (b) catch (Test t) (c) catch (…) (d) catch (Test) 4. How to handle error in the destructor? (a) throwing (b) terminate (c) both throwing & terminate CU IDOL SELF LEARNING MATERIAL (SLM)

(d) try 5.What kind of exceptions are available in C++? (a) handled (b) unhandled (c) static (d) dynamic Answers 1. (c), 2. (b), 3. (c), 4. (b), 5. (b) 8.9REFERENCES  Accelerated C++: Practical Programming by Example by Andrew Koenig and Barbara E. Mo  C++ Primer (5th Edition) 5th Edition by Stanley B. Lippman, Josee Lajoie, and Barbara E. Moo  Effective Modern C++: 42 Specific Ways to Improve Your Use of C++11 and C++14 (1st Edition) by Scott Meyers  Exceptional C++: 40 New Engineering Puzzles, Programming Problems, and Solutions by Herb Suttee  https://www.tutorialspoint.com/cplusplus/cpp_exceptions_handling.ht  https://www.w3schools.com/cpp/cpp_exceptions.asp  https://www.studytonight.com/cpp/exception-handling-in-cpp.php  L. Cardelli, J. Donahue, L. Glassman, M. Jordan, B. Kalsow, G. Nelson: Modula-3 Report. DEC Systems Research Center. August 1988.  Flaviu Cristian: Exception Handling. in Dependability of Resilient Computers, T. Andersen Editor, BSP Professional Books, Blackwell Scientific Publications, 1989.  Margaret A. Ellis and Bjarne Stroustrup: The Annotated C++ Reference Manual. Addison Wesley 1990.  J. Goodenough: Exception Handling: Issues and a Proposed Notation. CACM 207 CU IDOL SELF LEARNING MATERIAL (SLM)

December 1975 Steve C. Glassman and Michael J. Jordan: Safe Use of Exceptions. Personal communication 208 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 9 POINTER & VIRTUAL FUNCTION 209 Structure 9.0 LearningObjectives 9.1 Introduction 9.2 Understanding Pointers 9.2.1Pointer Variables 9.3 Declaring pointers 9.3.1 Accessing Address of Variable 9.3.2 Pointer Expressions 9.3.3 Pointer Initialization 9.3.3.1 The this Pointer 9.4 Pointer to Pointer 9.5 pointer to derived classes 9.6 Virtual Functions 9.6.1 Static and dynamic binding 9.7 Summary 9.8 KeyWords/Abbreviations 9.9 LearningActivity 9.10 Unit End Questions (MCQ andDescriptive) 9.11 References CU IDOL SELF LEARNING MATERIAL (SLM)

9.0 LEARNINGOBJECTIVES After studying this unit, you will be able to:  Identify the understanding pointers  Demonstrate the accessing address of a variable  Recognize the declaring and initializing pointers  Describe the pointer to pointer  Explain the pointer to a function  Explain static and dynamic binding. 9.1 INTRODUCTION Computers use their memory for storing instructions of the programs and the values of the variables. Memory is a sequential collection of storage cells. Each cell has an address associated with it. Whenever we declare a variable, the system allocates, somewhere in the memory, a memory location and a unique address is assigned to this location. 9.2 UNDERSTANDING POINTERS Pointer is a variable which can hold the address of a memory location rather than the value at the location. Consider the following statement: int num = 84; This statement instructs the system to reserve a 2-byte memory location and puts the value 84 in that location. Assume that a system allocates memory location 1001 for num. Diagrammatically, it can be shown as: 210 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 9.1Two byte memory location As the memory addresses are numbers, they can be assigned to some other variable. Let ptr be the variable which holds the address of variable num. Thus, we can access the value of num by the variable ptr. Thus, we can say “ptr points to num”. Diagrammatically, it can be shown as Fig 9.2 Pointer two numbers Pointers help in allocating memory dynamically. Pointers improve execution time and saves space 9.2.1Pointer Variables Pointers are variables that follow all the usual naming rules of regular, non-pointer variables. As with regular variables, you must declare pointer variables before you use them. A type of pointer exists for every data type in C++; you can use integer pointers, characters pointers, floating-point pointers, floating-point pointer, and so on. You can declare global pointer or local pointer, depending on where you declare them. The only difference between pointer variables and regular variables is what they hold. Pointer does not contain values, but the address of a value. C++ has two operators: 211 CU IDOL SELF LEARNING MATERIAL (SLM)

1. & - The “address of” operator 2. * - The de-referencing operator Whenever you see ‘&’ used with pointer, think of the phrase “address of”. The ‘&’ operator provides the memory address of whatever variable it precedes. The * operator, when used withpointer, de-references the pointer’s value. When you see * operator used, think of the phrase Notes “value pointed to”. 9.3 DECLARING POINTERS A pointer is a special variable that return the address of a memory. If you need to declare a variable to hold your age, you might use the following variable declaration: int age = 18 // declares to variable to hold my age Declaring age this way does several things. Because C++ knows that you need a variable called age, C++ reserves storage for that variable. C++ also knows that you will store only integers in age, not floating-point or double floating point data. You also have requested that C++ store the value of 18 in age after reserving storage for that variable. Suppose that you want to declare a pointer variable, not to hold your age but to point to age, the variable that hold your age. p_age might be a good name for this pointer variable. Figure given below shows an illustration of what you want to do. This example assumes that C++ store age at address 1002, although your C++ compiler arbitrarily determines the address of age, and it could be anything. To declare the p_age pointer variable You should do the following: int*_age; // declare an integer pointer As with the declaration for age, this line reserves a variable called p_age. It is not a normal integer variable, however, because of the C++ knows that this variable is to be a pointer 212 CU IDOL SELF LEARNING MATERIAL (SLM)

variable. 9.3Page Contains the Address of Age; p_age to the Age Variable Example: 9.3.1 Accessing Address of Variable 213 Consider the following statements: int q, * i, n; q = 35; i = & q; n = * i; CU IDOL SELF LEARNING MATERIAL (SLM)

i is a pointer to an integer containing the address of q. In the fourth statement we have assigned the value at address contained in i to another variable n. Thus, indirectly we have accessed the variable q through n using pointer variable i. 9.3.2 Pointer Expressions Like other variables, pointer variables can be used in expressions. Arithmetic and comparison operations can be performed on the pointers Example: If p1 and p2 are properly declared and initialized pointers, then following statements are valid. y = * p1 * *p2; sum = sum + * p1; 9.3.3 Pointer Initialization When declaring pointers we may want to explicitly specify which variable we want them to point to: int number; int *tommy = &number; The behavior of this code is equivalent to: int number; int *tommy; tommy = &number; When a pointer initialization takes place we are always assigning the reference value to where the pointer points (tommy), never the value being pointed (*tommy). You must consider that at the moment of declaring a pointer, the asterisk (*) indicates only that it is a pointer, it is not the dereference operator (although both use the same sign: *). Remember, 214 CU IDOL SELF LEARNING MATERIAL (SLM)

they are two different functions of one sign. Thus, we must take care not to confuse the previous code with: int number; int *tommy; *tommy = &number; that is incorrect, and anyway would not have much sense in this case if you think about it. As in the case of arrays, the compiler allows the special case that we want to initialize the content at which the pointer points with constants at the same moment the pointer is declared: char * terry = “hello”; In this case, memory space is reserved to contain “hello” and then a pointer to the first character of this memory block is assigned to terry. If we imagine that “hello” is stored at the memory locations that start at addresses 1702, we can represent the previous declaration as: 9.4 pointer declaration It is important to indicate that terry contains the value 1702, and not ‘h’ nor “hello”, although 1702 indeed is the address of both of these. The pointer terry points to a sequence of characters and can be read as if it was an array (remember that an array is just like a 215 CU IDOL SELF LEARNING MATERIAL (SLM)

constant pointer). Example: We can access the fifth element of the array with any of these two expressions: *(terry+4) terry [4] Both expressions have a value of ‘o’ (the fifth element of the array) 9.3.3.1The this Pointer C++ uses a unique keyword called “this” to represent an object that invokes a member function. ‘this’ is a pointer that points to the object on which this function was called. The pointer ‘this’ acts as an implicit argument to all the member function apart from the explicit arguments passed to it.When a number of objects are created from the same class each object’s data members are created as separate copies. However, only a single copy of methods is retained in the memory. That is all objects of a class share a single copy of the compiled class functions. A particular object is referenced by “this” pointer internally.Consider the following code snippet 216 CU IDOL SELF LEARNING MATERIAL (SLM)

When the code is executed, two marks variables are created - one for vibhor and one for prashant, but only one copy of setMarks function is kept in the memory (see the figure below). Fig 9.5 Use of this pointer 217 9.4 POINTER TO POINTERS CU IDOL SELF LEARNING MATERIAL (SLM)

Pointer is a variable, which contains address of a variable. This variable itself could be another pointer. Thus, a pointer contains another pointer’s address as shown in the example given below: The following figure would help you in tracing out how a program prints the output Output: Address of i = 6485 Address of i = 6485 Address of i = 6485 218 CU IDOL SELF LEARNING MATERIAL (SLM)

Address of j = 3276 Address of j = 3276 Address of k = 7234 Value of j = 6485 Value of k = 3276 Value of i = 3 Value of i = 3 Value of i = 3 Value of i = 3 9.5POINTER TO DERIVED CLASSES In C++, we can declare a pointer points to the base class as well as derive class. Consider below example to understand pointer to derived class Program #include<iostream.h> class base { public: int n1; void show() { cout<<”\\nn1 = “<<n1; } 219 CU IDOL SELF LEARNING MATERIAL (SLM)

}; class derive : public base { public: int n2; void show() { cout<<”\\nn1 = “<<n1; cout<<”\\nn2 = “<<n2; } }; int main() { base b; base *bptr; //base pointer cout<<”Pointer of base class points to it”; bptr=&b; //address of base class bptr->n1=44; //access base class via base pointer bptr->show(); derive d; cout<<”\\n”; bptr=&d; //address of derive class bptr->n1=66; //access derive class via base pointer bptr->show(); return 0; } Output Pointer of base class points to it n1 = 44 220 CU IDOL SELF LEARNING MATERIAL (SLM)

Pointer of base class points to derive class n1=66 Here the show() method is the overridden method, bptr execute show() method of ‘base’ class twice and display its content. Even though bptr first points to ‘base’ and second time points to ‘derive’ ,both the time bptr->show() executes the ‘base’ method show() 9.6 VIRTUAL FUNCTION Virtual functions, one of advanced features of OOP is one that does not really exist but it appears real in some parts of a program. This section deals with the polymorphic features which are incorporated using the virtual functions. The general syntax of the virtual function declaration is: class use_defined_name { private: public: virtual return_type function_name1 (arguments); virtual return_type function_name2(arguments); virtual return_type function_name3( arguments); ——————— ——————— }; To make a member function virtual, the keyword virtual is used in the methods while it is declared in the class definition but not in the member function definition. The keyword 221 CU IDOL SELF LEARNING MATERIAL (SLM)

virtual precedes the return type of the function name. The compiler gets information from the keyword virtual that it is a virtual function and not a conventional function declaration. Example: The following declaration of the virtual function is valid Remember that the keyword virtual should not be repeated in the definition if the definition occurs outside the class declaration. The use of a function specifier virtual in the function definition is invalid. A virtual function cannot be a static member since a virtual member is always a member of a particular object in a class rather than a member of the class as a whole. 9.6.1 Static and dynamic binding Static Binding: By default, matching of function call with the correct function definition 222 CU IDOL SELF LEARNING MATERIAL (SLM)

happens at compile time. This is called static binding or early binding or compile-time binding. Static binding is achieved using function overloading and operator overloading. Even though there are two or more functions with same name, compiler uniquely identifies each function depending on the parameters passed to those functions. Program to illustrate early binding. // Any normal function call (without virtual) // is binded early. Here we have taken base // and derived class example so that readers // can easily compare and see difference in // outputs. #include<iostream> using namespace std; class Base { public: void show() { cout<<\" In Base \\n\"; } }; class Derived: public Base { public: 223 CU IDOL SELF LEARNING MATERIAL (SLM)

void show() { cout<<\"In Derived \\n\"; } }; int main(void) { Base *bp = new Derived; // The function call decided at // compile time (compiler sees type // of pointer and calls base class // function. bp->show(); return 0; } Output: In Base Dynamic Binding: C++ provides facility to specify that the compiler should match function calls with the correct definition at the run time; this is called dynamic binding or late binding or run-time binding. Dynamic binding is achieved using virtual functions. Base class pointer points to derived class object. And a function is declared virtual in base class, then the matching function is identified at run-time using virtual table entry. 224 CU IDOL SELF LEARNING MATERIAL (SLM)

CPP Program to illustrate late binding #include<iostream> using namespace std; class Base { public: virtual void show() { cout<<\" In Base \\n\"; } }; class Derived: public Base { public: void show() { cout<<\"In Derived \\n\"; } }; int main(void) { Base *bp = new Derived; bp->show(); // RUN-TIME POLYMORPHISM return 0; } Output: 225 CU IDOL SELF LEARNING MATERIAL (SLM)

In Derived 9.7 SUMMARY  A pointer is a variable that holds the memory address of the location of another variable in memory. A pointer is declared in the following form: type * var_name ; where type is a predefined C++ data type and var_name is the name of the pointer variable  The operator &, when placed before a variable, returns the memory address of its operand. The operator * returns the memory address of its operand.  The operator * returns the data value stored in the area being pointed to by the pointer following it.  The pointer variables must always point to the correct type of data. Pointers must be initialized properly because uninitialized pointers result in the system crash.  In pointer arithmetic, all pointers increase and decrease by the length of the data type point to. 226 CU IDOL SELF LEARNING MATERIAL (SLM)

 An array name is a pointer that stores the address of its first element. If the array name is incremented, It actually points to the next element of the array. Array of pointers makes more efficient use of available memory. Generally, it consumes lesser bytes than an equivalent multi-dimensional array.  Functions can be invoked by passing the values of arguments or references to arguments or pointers to arguments.  When references or pointers are passed to a function, the function works with the original copy of the variable. A function may return a reference or a pointer also.  Virtual functions do not really exist but it appears real in some parts of a program. To make a member function virtual, the keyword virtual is used in the methods while it is declared in the class definition but not in the member function definition.  Early binding refers to the events that occur at compile time while late binding means selecting function during the execution. The late binding is implemented through virtual function. 9.8KEY WORDS/ABBREVIATIONS  Base Address: Starting address of a memory location holding array elements.  Function Pointer: A function may return a reference or a pointer variable also. A pointer to a function is the address where the code for the function resides. Pointer to functions can be passed to functions, returned from functions, stored in arrays and assigned to other pointers. Memory location: A container that can store a binary number.  Pointer: A variable holding a memory address. 227 CU IDOL SELF LEARNING MATERIAL (SLM)

 Late Binding: Selecting functions during the execution. Though late binding requires some overhead it provides increased power and flexibility.  Virtual Function: Virtual functions, one of advanced features of OOP is one that does not really exist but it appears real in some parts of a program 9.9LEARNINGACTIVITY 1. WAP that demonstrates dynamic binding. __________________________________________________________________________ __________________________________________________________________________ 2. WAP that demonstrates pointer to derived classes __________________________________________________________________________ __________________________________________________________________________ 9.10UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive Types Questions 1 Write a small program to show the difference between calling a virtual function inside a normal member function and calling a virtual function inside a constructor. The program should prove that the two calls produce different results. 2 In Early.cpp, how can you tell whether the compiler makes the call using early or late binding? Determine the case for your own compiler. 3 In AddingVirtuals.cpp, make all the member functions of Pet pure virtual, but provide a definition for name( ). Fix Dog as necessary, using the base-class definition of name( ). 4 Create a class that has a data member and a derived class that adds another data member. Write a non-member function that takes an object of the base class by 228 CU IDOL SELF LEARNING MATERIAL (SLM)

value and prints out the size of that object using sizeof. In main( ) create an object of the derived class, print out its size, and then call your function. Explain what happens. 5 Create a simple example of a virtual function call and generate assembly output. Locate the assembly code for the virtual call and trace and explain the code B. Multiple Choice Questions 1. Which class is used to design the base class? (a) abstract class (b) derived class (c) base class (d) derived & base class 2. Which is used to create a pure virtual function? (a) $ (b) =0 (c) & (d)! 3. Which is also called as abstract class? (a) virtual function (b) pure virtual function (c) derived class (d) base class 4. What is meant by pure virtual function? (a) Function which does not have definition of its own (b) Function which does have definition of its own (c) Function which does not have any return type (d) Function which does not have any return type & own definition 5. Where does the abstract class is used? 229 CU IDOL SELF LEARNING MATERIAL (SLM)

(a) base class only (b) derived class (c) both derived & base class (d) virtual class Answers 1. (a), 2. (b), 3. (b), 4. (a), 5(a) 9.11 REFERENCES  Horstman (2003). Computing Concept with C++ Essentials. New Delhi: John Wiley.  Easttom C. (2010). C++ Programming Fundamentals. Delhi: Firewall Media.  Programming in C++” by Mahapatra P B  Object-Oriented Programming with C++” by A K Sharma  Amma, Helm, Johnson, Vlissides (GoF) – Design Patterns Elements of Reusable Object-Oriented Software  Herb Sutter – Exceptional C++: 47 Engineering Puzzles, Programming Problems, and Solutions  Object Oriented Programming with C++; Cyber tech publications  http://publib.boulder.ibm.com/infocenter/comphelp/v8v101 index.jsp?topic= %2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr035.htm  http://www.cplusplus.com/doc/tutorial/pointers/  http://www.artima.com/cppsource/pure_virtual.html  http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic= %2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr142.htm  https://codescracker.com/cpp/cpp-declaring-initializing-pointers.htm  https://www.xspdf.com/resolution/52190469.html  https://www.geeksforgeeks.org/pointers-c-examples/  Scott Meyers – Effective C++: 55 Specific Ways to Improve Your Programs and 230 CU IDOL SELF LEARNING MATERIAL (SLM)

Designs  Scott Meyers – More Effective C++: 35 New Ways to Improve Your Programs and Designs UNIT 10 DYNAMIC MEMORY ALLOCATION 231 Structure 10.0 LearningObjectives 10.1 Introduction 10.2 Dynamic memory allocation 10.3 New and Delete operator 10.3.1 Operators new and new[ ] 10.3.2 Operators n delete and delete [ ] 10.4 Summary 10.5 KeyWords/Abbreviations 10.6 LearningActivity 10.7 Unit End Questions (MCQ andDescriptive) 10.8 Suggested Readings 10.0 LEARNINGOBJECTIVES After studying this unit, you will be able to: CU IDOL SELF LEARNING MATERIAL (SLM)

 Discuss the dynamic memory management  Explain Dynamic memory allocation using new and delete operator 10.1 INTRODUCTION Dynamic memory allocation using new and delete operator. A good understanding of how dynamic memory really works in C++ is essential to becoming a good C++ programmer. Memory in your C++ program is divided into two parts − The stack − All variables declared inside the function will take up memory from the stack. The heap − this is unused memory of the program and can be used to allocate the memory dynamically when program runs Many times, you are not aware in advance how much memory you will need to store particular information in a defined variable and the size of required memory can be determined at run time. You can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. If you are not in need of dynamically allocated memory anymore, you can use delete operator, which de-allocates memory previously allocated by new operator. 10.2DYNAMIC MEMORY ALLOCATION Dynamic memory is allocated by the new keyword. Memory for one variable is allocated as below: ptr=new DataType (initializer); Here, 232 CU IDOL SELF LEARNING MATERIAL (SLM)

1. ptr is a valid pointer of type DataType. 2. DataType is any valid C++ data type. 3. Initializer (optional) if given, the newly allocated variable is initialized to that value. Example: //Example Program in C++ This is will allocate memory for an int(eger) having initial value 10, pointed by the ptr pointer. Memory space for arrays is allocated as shown below: ptr=new DataType [x]; Here, 1. ptr and DataType have the same meaning as above. 2. x is the number of elements and C is a constant. Example: 233 CU IDOL SELF LEARNING MATERIAL (SLM)

10.3 NEW AND DELETE OPERATOR Until now, in all our programs, we have only had as much memory available as we declared for our variables, having the size of all of them to be determined in the source code, before the execution of the program. But, what if we need a variable amount of memory that can only be determined during runtime? For example, in the case that we need some user input to determine the necessary amount of memory space. The answer is dynamic memory, for which C++ integrates the operators new and delete. 10.3.1 Operators new and new[] In order to request dynamic memory we use the operator new. New is followed by a data type specifier and – if a sequence of more than one element is required – the number of these within brackets [ ]. It returns a pointer to the beginning of the new block of memory allocated. Its form is: pointer = new type pointer = new type [number_of_elements] 234 CU IDOL SELF LEARNING MATERIAL (SLM)

The first expression is used to allocate memory to contain one single element of type type. The Notes second one is used to assign a block (an array) of elements of type type, where number_of_elements is an integer value representing the amount of these. For example: int * bobby; bobby = new int [5]; In this case, the system dynamically assigns space for five elements of type int and returns a pointer to the first element of the sequence, which is assigned to bobby. Fig 10.1Space for five elements The first element pointed by bobby can be accessed either with the expression bobby[0] or the expression *bobby. Both are equivalent as has been explained in the section about pointers. The second element can be accessed either with bobby[1] or *(bobby+1) and so on... You could be wondering the difference between declaring a normal array and assigning dynamic memory to a pointer, as we have just done. The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size. The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, it is important to have some mechanism to check if our request to allocate memory was successful or not. C++ provides two standard methods to check if the allocation was successful: One is by handling exceptions. Using this method an exception of type bad_alloc is thrown when the allocation fails. Exceptions are a powerful C++ feature explained later in these tutorials. But for now you should know that if this exception is thrown and it is not handled by a specific handler, 235 CU IDOL SELF LEARNING MATERIAL (SLM)

the program execution is terminated. This exception method is the default method used by new, and is the one used in a declaration like: bobby = new int [5]; // if it fails an exception is thrown The other method is known as nothrow, and what happens when it is used is that when a memory allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution. This method can be specified by using a special object called nothrow, declared in header , as argument fornew: bobby = new (nothrow) int [5]; The first element pointed by bobby can be accessed either with the expression bobby[0] or the expression *bobby. Both are equivalent as has been explained in the section about pointers. The second element can be accessed either with bobby[1] or *(bobby+1) and so on... You could be wondering the difference between declaring a normal array and assigning dynamic memory to a pointer, as we have just done. The most important difference is that the size of an array has to be a constant value, which limits its size to what we decide at the moment of designing the program, before its execution, whereas the dynamic memory allocation allows us to assign memory during the execution of the program (runtime) using any variable or constant value as its size. The dynamic memory requested by our program is allocated by the system from the memory heap. However, computer memory is a limited resource, and it can be exhausted. Therefore, it is important to have some mechanism to check if our request to allocate memory was successful or not. C++ provides two standard methods to check if the allocation was successful: One is by handling exceptions. Using this method an exception of type bad_alloc is thrown when the allocation fails. Exceptions are a powerful C++ feature explained later in these tutorials. But for now you should know that if this exception is thrown and it is not handled by a specific handler, the program execution is terminated. This exception method is the default method used by new, and is the one used in a declaration like: 236 CU IDOL SELF LEARNING MATERIAL (SLM)

bobby = new int [5]; // if it fails an exception is thrown The other method is known as nothrow, and what happens when it is used is that when a memory allocation fails, instead of throwing a bad_alloc exception or terminating the program, the pointer returned by new is a null pointer, and the program continues its execution. This method can be specified by using a special object called nothrow, declared in header , as argument In this case, if the allocation of this block of memory failed, the failure could be detected by checking if bobby took a null pointer value: int * bobby; bobby = new (nothrow) int [5]; if (bobby == 0) { // error assigning memory. Take measures. }; Anyway this method can become tedious for larger projects, where the exception method is generally preferred. 10.3.2 Operators delete and delete[ ] Since the necessity of dynamic memory is usually limited to specific moments within a program, once it is no longer needed it should be freed so that the memory becomes available again for other requests of dynamic memory. This is the purpose of the operator delete, whose format is: delete pointer; delete [ ] pointer; The first expression should be used to delete memory allocated for a single element, and the second one for memory allocated for arrays of elements. The value passed as argument to delete must be either a pointer to a memory block previously allocated with new, or a null pointer (in the case of a null pointer, delete produces no effect). 237 CU IDOL SELF LEARNING MATERIAL (SLM)

Enter number : 75 Enter number : 436 238 CU IDOL SELF LEARNING MATERIAL (SLM)

Enter number : 1067 Enter number : 8 Enter number : 32 You have entered: 75, 436, 1067, 8, 32, Notice how the value within brackets in the new statement is a variable value entered by the user (i), not a constant value: p= new (nothrow) int[i]; But the user could have entered a value for i so big that our system could not handle it. For example, when I tried to give a value of 1 billion to the “How many numbers” question, my system could not allocate that much memory for the program and I got the text message we prepared for this case (Error: memory could not be allocated). It is a good practice to always check if a dynamic memory block was successfully allocated. Therefore, if you use the nothrow method, you should always check the value of the pointer returned. Otherwise, use the exception method, even if you do not handle the exception. This way, the program will terminate at that point without causing the unexpected results of continuing executing a code that assumes a block of memory to have been allocated when in fact it has not. 10.4 SUMMARY  Dynamic memory allocation in C/C++ refers to performing memory allocation manually by programmer. Dynamically allocated memory is allocated on Heap and non-static and local variables get memory allocated on Stack  There are essentially two types of memory allocation Static – Done by the compiler automatically (implicitly).  Global variables or objects -- memory is allocated at the start of the program, and freed when program exits; alive throughout program execution  Can be access anywhere in the program. 239 CU IDOL SELF LEARNING MATERIAL (SLM)

 Local variables (inside a routine) – memory is allocated when the routine starts and freed when the routine returns.  A local variable cannot be accessed from another routine.  Allocation and free are done implicitly.  No need to explicitly manage memory is nice (easy to work with), but has limitations! Using static allocation, the array size must be fixed.  There are essentially two types of memory allocation  Dynamic memory allocation deals with this situation. Dynamic – Done explicitly by programmer.  Programmer explicitly requests the system to allocate memory and return starting address of memory allocated (what is this?). This address can be used by the programmer to access the allocated memory. When done using memory, it must be explicitly freed.  the ‘delete’ Operator - Used to free memory allocated with new operator  The delete operator should be called on a pointer to dynamically allocated memory when it is no longer needed  You can change the behavior of new and delete if they don’t suit your needs, particularly if they aren’t efficient enough. Also, you can modify what happens when the heap runs out of storage. 10.5KEY WORDS/ABBREVIATIONS  Memory location: A container that can store a binary number.  Pointer: A variable holding a memory address.  Reference: An alias for a pointer that does not require de-referencing to use  Delete operator: C++ keyword and operator used to delete dynamic storage.  Delete [] operator: used to delete array objects.  Deallocation: the processing of freeing memory space previously used by an object 240 CU IDOL SELF LEARNING MATERIAL (SLM)

10.6LEARNINGACTIVITY 1. Write a program that reads a group of numbers from the user and places them in an array of type float. Once the numbers are stored in the array, the program should average them and print the result. Use pointer notation wherever possible. __________________________________________________________________________ __________________________________________________________________________ 2. WAP to understand the concept of new and delete operator. __________________________________________________________________________ __________________________________________________________________________ 10.7 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive Types Questions 1. Create a program, which reads an n dimensional vector v of doubles and reads A an n × n matrix (linear transformation) and prints the resulting vector after applying the transformation A (ie, A × v). n, the dimension, should also be read from the keyboard, and A and v should be dynamically allocated. 2. Modify a procedure, which returns a pointer to the transpose of an n×m dynamically allocated matrix. 3. Create a vector< Counted*> and fill it with pointers to new Counted objects (from Exercise 1). Move through the vector and print the Counted objects, then move through again and delete each one. 4. Create an object of class Counted(from Exercise 1) using new, cast the resulting pointer to a void*, and delete that. Explain the results. 5. Create a class Counted that contains an int id and a static int coun. The default constructor should begin: t Counted( ) : id(count++). It should also print its { id and 241 CU IDOL SELF LEARNING MATERIAL (SLM)

that it’s being created. The destructor should print that it’s being destroyed and its id. Test your class B. Multiple Choice Questions 1. Local variables are stored in an area called ___________ (a) Heap (b) Permanent storage area (c) Free memory (d) Stack 2. Choose the statement which is incorrect with respect to dynamic memory allocation. (a) Memory is allocated in a less structured area of memory, known as heap (b) Used for unpredictable memory requirements (c) Execution of the program is faster than that of static memory allocation (d) Allocated memory can be changed during the run time of the program based on the requirement of the program 3. Which of the following header files must necessarily be included to use dynamic memory allocation functions? (a) stdlib.h (b) stdio.h (c) memory.h (d) dos.h 4. Which of the following is an example for nonlinear data type? (a) Tree (b) Array (c) Linked list (d) Queue 5. Queue data structure works on the principle of ____________ 242 CU IDOL SELF LEARNING MATERIAL (SLM)

(a) Last in First Out (LIF0) (b) First in Last Out (FILO) (c) First in First Out (FIFO) (d) Last in Last Out (LILO) Answers 1. (d), 2. (c), 3. (a), 4. (a), 5. (c) 10.8 REFERENCES  Modern C++ Design: Generic Programming and Design Patterns Applied  More Effective C++by Scott Meyers  Effective C++: 55 Specific Ways to Improve Your Programs and Designs by Scott Meyers  C++ Coding Standards: 101 Rules, Guidelines, and Best Practices by Herb Sutter  https://www.geeksforgeeks.org/new-and-delete-operators-in-cpp-for-dynamic- memory/  http://publib.boulder.ibm.com/infocenter/comphelp/v8v101index.jsp?topic= %2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr035.htm  http://www.cplusplus.com/doc/tutorial/dynamic/  https://fresh2refresh.com/cpp-tutorial/cpp-dynamic-memory-allocation/  Dynamic Memory Allocation: Role in Memory Management March 2014Authors:Prabhudev Irabashetti  Memory Management Techniques: Static and Dynamic Memory AllocationAuthor : Supriya Pralhad Mali, Sonali Dohe and Priya RangdaPages : 92- 94  Review Of Memory Allocation And Management In Computer Systems Ahmed Faraz 243 CU IDOL SELF LEARNING MATERIAL (SLM)

244 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 11 FILES 245 Structure 11.0. LearningObjectives 11.1. Introduction 11.2. Concept of Streams 11.3. Hierarchy of Console Stream Classes 11.4. File operations 11.5. Unformatted I/O Operations 11.6. Reading/Writing of files 11.7. Summary 11.8. KeyWords/Abbreviations 11.9. LearningActivity 11.10.Unit End Questions (MCQ andDescriptive) 11.11. References 11.0 LEARNINGOBJECTIVES After studying this unit, you will be able to:  Recognize the concepts of streams  Describe the hierarchy of console stream classes  Explain the unformatted I/O operations  Unformatted I/O Operations  Explain Reading/Writing of files. CU IDOL SELF LEARNING MATERIAL (SLM)

11.1 INTRODUCTION One of the most essential features of interactive programming is its ability to interact with the users through operator console usually comprising keyboard and monitor. Accordingly, every computer language (and compiler) provides standard input/output functions and/or methods to facilitate console operations. C++ accomplishes input/output operations using concept of stream. A stream is a series of bytes whose value depends on the variable in which it is stored. This way, C++ is able to treat all the input and output operations in a uniform manner. Thus, whether it is reading from a file or from the keyboard, for a C++ program it is simply a stream. We have used the objects cin and cout (predefined in the iostream.h file) for the input and output of data of various types. This has been made possible by overloading the operators >> and << to recognize all the basic C++ types. The >> operator is overloaded in the istream class and << is overloaded in the ostream class. The following is the general format for reading data from the keyboard: cin >> variable1 >> variable2 >>.. ...>> variableN; where variable1, variable2, . . .. are valid C++ variable names that have been declared already. Notes This statement will cause the computer to halt the execution and look for input data from the keyboard. The input data for this statement would be: datal data2……dataN The input data are separated by white spaces and should match the type of variable in the cin list. Spaces, new lines and tabs will be skipped. The operator >> reads the data character by character and assigns it to the indicated location. The reading for a variable will be terminated at the encounter of a white space or a character that does not match the destination type. For example, consider the following code: int code; cin >> code; Suppose the following data is given as input: 246 CU IDOL SELF LEARNING MATERIAL (SLM)

1267E The operator will read the characters up to 7 and the value 1267 is assigned to code. The character E remains in the input stream and will be input to the next cin statement. The general format of outputting data: cout << iteml <<< .. ..<< itemN; 11.2 CONCEPT OF STREAMS A stream is a source of sequence of bytes. A stream abstracts for input/output devices. It can be tied up with any I/O device and I/O can be performed in a uniform way. The C++ iostream library is an object-oriented implementation of this abstraction. It has a source (producer) of flow of bytes and a sink (consumer) of the bytes. The required classes for the stream I/O are defined in different library header files. To use the I/O streams in a C++ program, one must include iostream.h header file in the program. This file defines the required classes and provides the buffering. Instead of functions, the library provides operators to carry out the I/O. Two of the Stream Operators are: << : Stream insertion for output. >> : Stream extraction for input. The following streams are created and opened automatically: cin: Standard console input (keyboard). cout: Standard console output (screen). cprn : Standard printer (LPT1). cerr : Standard error output (screen). clog : Standard log (screen). caux: Standard auxiliary (screen). 247 CU IDOL SELF LEARNING MATERIAL (SLM)

Example: The following program reads an integer and prints the input on the console 11.3 HIERARCHY OF CONSOLE STREAM CLASSES Streams can also be tied up with data files. The required stream classes for file I/O are defined in fstream.h and/or strstream.h. fstream : File I/O class. Table 11.1 fstream : File I/O class 248 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 11.1 Hierarchy of file stream classes There are some special functions that can alter the state the stream. These functions are called manipulators. Stream manipulators are defined in iomanip.h. Table 11.1 Stream manipulators dec Sets base 10 integers. endl Sends a new line character. ends Sends a null (end of string) character. flush Flushes an output stream. fixed Sets fixed real number notation. hex Sets base 16 integers. Oct Sets base 8 integers. ws Discard white space on input. setbase(int)Sets integer conversion base (0, 8, 10 or 16 where0 sets base 10). setfill(int) Sets fill character 249 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook