nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n

Size: px
Start display at page:

Download "nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n"

Transcription

1 Static and Dynamic Memory Allocation In this chapter we review the concepts of array and pointer and the use of the bracket operator for both arrays and pointers. We also review (or introduce) pointer arithmetic and the concepts of static and dynamic variable and compile time and run time binding. Static and Dynamic Values A variable that is named and declared in a program is said to be static and bound at compile time, meaning that the relationship between the identifier and its attributes (such as type and storage address) is fixed during the compilation of the program as an entry in the sybmol table. The following program fragment illustrates two declarations, of n and nptr. These are both static variables bound at compile time: int n; // binds "n" with storage for an int // binds "nptr" with storage for an address_of_int // NOTE: At this point, neither n nor nptr has a valid value -- // only the random junk left in that storage space // by some previous process or program nptr = new int; // assigns valid address_of_int value to nptr std::cin >> n; // assigns valid int value to n The third line of code in this fragment assigns a specific address the pointer variable nptr during the execution of the program, and at the same time assigns the use of the memory at this address to nptr. This line is executed during the run of the program. This memory represents a dynamic variable that is allocated and bound to *nptr at run time. These concepts are illusrated in the figure: Thus: nptr is static and bound at compile time, whereas *nptr is dynamic and bound at run time. 1/9

2 Pointer Dereference To dereference a pointer is to access the contents of the memory address that is the pointer's value. If p is a pointer, *p is the dereference of p. Thus "*" is a unary operator. Dereference is illustrated in the following code fragment: // declares nptr (static) nptr = new int; // assigns an int address to nptr (dynamic) *nptr = 3; // stores the value 3 at the address nptr std::cout << *nptr; // output is contents of the address nptr, i.e., "3" std::cout << nptr; // output is the (hexadecimal) address assigned to nptr Operator new T Operator new can be invoked for any proper type T. (A proper type is either a native type or a user defined type that possesses a full complement of constructors and destructor.) A call p = new T performs these essential tasks: 1. Allocates memory for (one) T object from the pool of available memory 2. Removes this memory from the available pool 3. Calls the default T constructor for the object 4. Returns the address of this T object and assigns it to p Operator new will take optional constructor parameters using (), which results in calling the T constructor with those parameters in step 3 above. Here is a code fragment illustrating a call to operator new: int n; BitVector* bvptr; cin >> n; bvptr = new BitVector(n); // static // static // give n a value // dynamic This code fragment declares the (static) vairables n and bvptr, establishes a value for n dynamically, and then creates a (dynamic) bitvector object of size n. Note that bvptr, like any other declared variable, has scope confined to the block in which it is declared. In contrast, *bvptr, the object created by operator new, has global scope. Thus it is quite possible (and in fact often the case) that bvptr goes out of scope leaving the unnamed entity *bvptr in scope. This situation must be carefully managed by the programmer. Operator delete Operator delete is the complementary operator to new, essentially reversing the effects of allocation. A call delete p performs these essential tasks: 1. Calls the T destructor for the object at address p 2. Returns the allocated memory at address p to the pool of available memory Note that operator delete should be called explicitly to de-allocate any memory that has been previously allocated with operator new. Failure to de-allocate memory is the primary cause of the 2/9

3 program defect called a memory leak, in which the memory allocated to the running program gradually increases until either it runs out of memory and crashes or uses so much virtual memory that the platform slows to a standstill. Here is a code fragment that de-allocates the memory allocated in the previous fragment. Note that these two complementary fragments may be widely separated in the source code and in the times in which they are called: delete bvptr; // calls BitVector destructor // de-allocates memory assigned to bvptr by new BitVector This code first calls the BitVectordestructor and then releases the memory previously assigned to bvptr. Note that the scope of *bvptr ends with the call delete bvptr. Operator new T [n] Operator new[] can be invoked for any proper type T and any size_t integer n. A call p = new T [n] performs these essential tasks: 1. Allocates a (contiguous) block of memory for n T objects from the pool of available memory 2. Removes this block of memory from the available pool 3. Calls the default T constructor for each object in the allocated block 4. Returns the address of the first T object in the block and assigns it to p These contiguous blocks of memory are called arrays. Operator new[] will take optional constructor parameters using (), which results in calling the T constructor with those parameters in step 3 above. Here is a code fragment illustrating calls to operator new[]: nptr = new int [20]; // array of 20 int BitVector* bvptr; bvptr = new BitVector (10) [20]; // array of bit BitVectors Operator delete [] Operator delete [] is the complementary operator to new [], essentially reversing the effects of allocation. A call delete [] p performs these essential tasks: 1. Calls the T destructor for each object in the block beginning at address p 2. Returns the allocated block at address p to the pool of available memory Note that operator delete [] should be called explicitly to de-allocate any memory that has been previously allocated with operator new []. A common programming oversight is to omit the [] in a call to delete. This error will successfully de-allocate the memory, but it will call the T destructor only for the first T object in the array. Thus the objects in the allocated array may not be correctly destroyed. Here is a code fragment that de-allocates the memory allocated in a previous fragment. Note that these two complementary fragments may be widely separated in the source code and in the times in which they are called: 3/9

4 delete [] bvptr; // calls BitVector destructor for all 20 bitvectors // de-allocates block of memory assigned to the array Arrays Arrays can be created either dynamically or statically. The dynamic array is created using operator new [] and destroyed using operator delete [], as described above. A static array is created with a declaration as in the following (choose static or dynamic): T A [n]; // static T* A = new T [n]; // dynamic Note that either of these lines creates an array of 20 T objects. Each form of the declaration uses the bracket operator to designate the size of the array. For either declaration: A[i] is (a reference to) the i th element, starting with index i = 0 *A and A[0] each refer to the 0 th, or first, element (see also "pointer arithmetic" below) A is the address of the 0 th, or first, element If A is declared as a static array, the usual scope rules apply, and it is created and destroyed automatically by the runtime system supporting the program. Also, when declared statically, the identifier A itself is a constant, whereas when declared dynamically, A is a variable. Thus for example: int a [20]; int* p = new int [20];... p = a; // OK a = p; // error - "a" is a constant p[i] = a[i]; // OK a[i] = p[i]; // OK There is more on this topic under the pointer arithmetic discussion. The Bracket Operator The bracket operator [] for an array is implemented by computing the address of the i th object, as follows: base = A = address of A[0] address of element i = base + offset = base + i * sizeof(t) A[i] = reference to element at this address The pointer A must know its type to compute addresses using sizeof(t). Note carefully the distinction between A and A[0]. 4/9

5 Pointer Arithmetic Pointers are variables of integral type, because addresses are integers. (Pointers also have information about the type to which they point.) Thus it makes sense to allow certain kinds of arithmetic for pointers. The unary operators ++ and -- (pre- and post-fix versions of each) ++p / --p increments/decrements the pointer p to the next/previous element of the array. (pointer) + (int) = (pointer) p + n moves the pointer p forward n elements in the array. (Note that if n is negative, this is really moving backward.) (pointer) - (pointer) = (int) p1 - p2 returns the number of elements that are between the two pointers. Note that these operations are defined only when they make sense. For example, if the two pointers p1 and p2 point into two different arrays, then p1 - p2 is not defined. Keeping in mind that each "unit" represents an entire object helps in remembering the rules for pointer arithmetic. Note also that pointer arithmetic gives an alternative syntax for accessing array elements. For example, suppose that we have one or the other of these declarations: int A [10]; int* A = new int [10]; Then these are alternative expressions with the same meaning: A = base address of allocated memory block A[0] = *A = reference to value stored at base address &A[3] = A + 3 = address of element at index 3 A[3] = *(A + 3) = reference to value stored at index 3 In fact the notation we learn first - A[i] - is often referred as "syntactical sugar" for the more fundamental expression *(A + i). Pointer Arithmetic Example 1 // T is some type T* A = new T [20]; // A is the address of the first (index 0) T object T* B; // B can store an address for T, but has no valid value ++A; // now A is the address of the second (index 1) object B = A--; // assigns B the value of A, then decrements A ++B; // increments B; now B points to the index 2 element of A std::cout << B - A; // output is 2, the difference between the indexes A = B + 3; // now A is the address of the index 5 element The following illustrates the use of pointer arithmetic in loop control variables: char A [10] = 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'; char * i, * j, * k; for (i = A; i!= A + 10; ++i) for (j = A; j!= A + 10; ++j) for (k = A; k!= A + 10; ++k) std::cout *i << *j << *k << '\n'; 5/9

6 Note the convenience of using three aliases for a single array as loop control variables that dereference to array elements. Pointer Arithmetic Example 2 Code: unsigned int i; char* A = new char [4]; for (i = 0; i < 4; ++i) A[i] = char(i + int('a')); for (i = 0; i < 4; ++i) cout << "A[" << i << "] == " << A[i] << '\n'; x = A++; cout << *x << ' ' << A[0] << '\n'; x = ++A; cout << *x << ' ' << A[1] << '\n'; Output: A[0] == a A[1] == b A[2] == c A[3] == d a b c d Binding Time const int c(15); int n; cin >> n; n = c; nptr = new int; *nptr = n; delete nptr; // compile time binding // static memory allocation of type int // compile time valuation // static valuation // compile time binding // static memory allocation of type int // run time valuation / dynamic valuation // run time valuation / dynamic valuation // compile time binding // static memory allocation of type int* // run time binding // dynamic memory allocation of type int // run time valuation / dynamic valuation // run time unbinding Scope of Dynamic Variables We have discussed the scope of statically bound variables in previous chapters. The one point to add about dynamic variables is: dynamic variables have global scope. The reason for insisting that items created with operator new have global scope is simple: it is not possible to predict when or in what part of the program the corresponding call to operator delete may occur. Only by giving the 6/9

7 variable allocated by new global scope can it be ensured that it will be accessible to operator delete when it is called. Note that in the following fragment repeated from above: nptr = new int; *nptr = n; delete nptr; // compile time binding // static memory allocation of type int* // run time binding // dynamic memory allocation of type int // run time valuation / dynamic valuation // run time unbinding the usual scope rules apply to both n and nptr. However, the variable allocated at *nptr has global scope. This variable remains in scope even after nptr goes out of scope! C Strings C strings suffer from all of the problems of primitive arrays plus a few extra problems unique to strings. All of these problems are of the nature of traps that victimize imperfect humans. These problems have two roots: 1. Memory management 2. Stop signs (null-termination) Now, please understand, imperfect people can write perfect programs. The problem is that imperfect people do not write perfect programs all the time. Perfection in programming requires high levels of totally focussed effort in analysis, design, and implementation. All of us can fulfill these requirements some of the time. There is no person who can do it all of the time. C strings open doors of bad opportunity that wait for us when we are not performing perfectly. Conceptually, a C string is a null-terminated array of characters. As a type, though, a C string is nothing more than a pointer to char. The mismatch between concept and type means there are assumptions that are not visible to or checkable by the preprocessor, compiler, or runtime system. These assumptions are: 1. Strings are null terminated 2. Memory for strings has been allocated There is no compiler check to ensure these assumptions are satisfied, even in when using the C string library declared in string.h. Here is some code illustrating hidden assumptions, together with some code that illustrates correct ways to instantiate the assumptions. // static: char str1 [11]; // static array of char str1[10] = '\0'; // null-terminate strcpy (str1, "abcdefghij"); // define the chars in the string // dynamic: char* str2; str2 = new char [11]; str2[10] = '\0'; strcpy (str2, str1); // pointer to char // dynamic array of char // null-terminate // define // operator <<(): cout << str1 << ' ' << str2 << '\n'; 7/9

8 The effect of the code is to create two strings and output them to screen. C String Functions This slide illustrates a typical implementation of the output operator overload for C strings. For those of us who are still a little uncomfortable with pointer notation, here is an alternative: ostream& operator << (ostream& os, char* str) int i = 0; while (str[i]!= '\0') os.put(str[i++]); return os; How is the assumption of null-termination used? The null-termination assumption is used to terminate the loop. Null-termination refers to the conceptual constraint that strings have "stop signs" (the null character '\0') to indicate when the data in memory is no longer part of the string. Without a stop sign, the loop in this function would run indefinitely, or at least until incrementation resulted in an invalid memory address. Long before this occurred, the loop would be running through memory that wasn't ever part of the string, and perhaps not even owned by the running program. The result would be a screen full of random junk, at best. How is the assumption of memory allocation used? Implicit in the process that copied str1 to str2 in the previous slide was an assumption that data was copying into memory that was reserved for the purpose. If memory had not been allocated correctly, the copy routine would not have any way to know, so it would copy data into memory that likely is used for some other important purpose, thus overwriting that memory and sabotaging that part of the program. What happens if the assumptions are not valid? Almost anything. Crashing programs, random or unpredictable results, even system crashes can and do happen due to mistakes with strings. The secondary consequences can be huge: failed critical systems, incorrectly functioning medical devices,... C String Functions (cont.) Here is another example, a possible implementation of strcpy(): void strcpy (char* str2, const char* str1) while (*str1!= '\0') *str2 = *str1; ++str2; ++str1; *str2 = '\0'; Note the following: 8/9

9 Assumption that str1 is null-terminated used implicitly Assumption that str2 has been allocated sufficient memory used implicitly In general, C string functions do not handle or "worry about" memory management. Most of the other string functions prototyped in string.h suffer from similar defects. In addition to trapping many an unwary programmer, these defects have been exploited by unethical hackers for destructive and criminal purposes, including such notorious incidents as the Internet Worm and unauthorized takeover of department of defense systems. The legacy of C is a mixed one. 9/9

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

POINTERS - Pointer is a variable that holds a memory address of another variable of same type. - It supports dynamic allocation routines. - It can improve the efficiency of certain routines. C++ Memory

More information

A brief introduction to C programming for Java programmers

A brief introduction to C programming for Java programmers A brief introduction to C programming for Java programmers Sven Gestegård Robertz September 2017 There are many similarities between Java and C. The syntax in Java is basically

More information

Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

More information

CSC 211 Intermediate Programming. Arrays & Pointers

CSC 211 Intermediate Programming. Arrays & Pointers CSC 211 Intermediate Programming Arrays & Pointers 1 Definition An array a consecutive group of memory locations that all have the same name and the same type. To create an array we use a declaration statement.

More information

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays

CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays CS107 Handout 08 Spring 2007 April 9, 2007 The Ins and Outs of C Arrays C Arrays This handout was written by Nick Parlante and Julie Zelenski. As you recall, a C array is formed by laying out all the elements

More information

Bits and Bytes. Bit Operators in C/C++

Bits and Bytes. Bit Operators in C/C++ Bits and Bytes The byte is generally the smallest item of storage that is directly accessible in modern computers, and symbiotically the byte is the smallest item of storage used by modern programming

More information

CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages CSE 307: Principles of Programming Languages Variables and Constants R. Sekar 1 / 22 Topics 2 / 22 Variables and Constants Variables are stored in memory, whereas constants need not be. Value of variables

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 31 Static Members Welcome to Module 16 of Programming in C++.

More information

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE? 1. Describe History of C++? The C++ programming language has a history going back to 1979, when Bjarne Stroustrup was doing work for his Ph.D. thesis. One of the languages Stroustrup had the opportunity

More information

Pointers and References

Pointers and References Steven Zeil October 2, 2013 Contents 1 References 2 2 Pointers 8 21 Working with Pointers 8 211 Memory and C++ Programs 11 212 Allocating Data 15 22 Pointers Can Be Dangerous 17 3 The Secret World of Pointers

More information

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor. 3.Constructors and Destructors Develop cpp program to implement constructor and destructor. Constructors A constructor is a special member function whose task is to initialize the objects of its class.

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #29 Arrays in C Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #29 Arrays in C (Refer Slide Time: 00:08) This session will learn about arrays in C. Now, what is the word array

More information

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II:

FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: FORM 2 (Please put your name and form # on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each): 1. The declaration below declares three pointer variables of type pointer to double that is

More information

Ch. 12: Operator Overloading

Ch. 12: Operator Overloading Ch. 12: Operator Overloading Operator overloading is just syntactic sugar, i.e. another way to make a function call: shift_left(42, 3); 42

More information

Short Notes of CS201

Short Notes of CS201 #includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

More information

Operator overloading

Operator overloading 1 Introduction 2 The copy constructor 3 Operator Overloading 4 Eg 1: Adding two vectors 5 The -> operator 6 The this pointer 7 Overloading = 8 Unary operators 9 Overloading for the matrix class 10 The

More information

CS201 - Introduction to Programming Glossary By

CS201 - Introduction to Programming Glossary By CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with

More information

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty! Chapter 6 - Functions return type void or a valid data type ( int, double, char, etc) name parameter list void or a list of parameters separated by commas body return keyword required if function returns

More information

Instantiation of Template class

Instantiation of Template class Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double

More information

Pointers and Dynamic Memory Allocation

Pointers and Dynamic Memory Allocation Pointers and Dynamic Memory Allocation ALGORITHMS & DATA STRUCTURES 9 TH SEPTEMBER 2014 Last week Introduction This is not a course about programming: It s is about puzzling. well.. Donald Knuth Science

More information

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming

KOM3191 Object Oriented Programming Dr Muharrem Mercimek OPERATOR OVERLOADING. KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 1 OPERATOR OVERLOADING KOM3191 Object-Oriented Programming KOM3191 Object Oriented Programming Dr Muharrem Mercimek 2 Dynamic Memory Management

More information

Ch. 11: References & the Copy-Constructor. - continued -

Ch. 11: References & the Copy-Constructor. - continued - Ch. 11: References & the Copy-Constructor - continued - const references When a reference is made const, it means that the object it refers cannot be changed through that reference - it may be changed

More information

WHAT POINTERS REALLY ARE

WHAT POINTERS REALLY ARE POINTERS What is a pointer? The index of a book contains pointers. A URL (e.g., http://turing.ubishops.ca/home/cs318) is a pointer. A street address is a pointer. What is then a forwarding address? a pointer

More information

VIRTUAL FUNCTIONS Chapter 10

VIRTUAL FUNCTIONS Chapter 10 1 VIRTUAL FUNCTIONS Chapter 10 OBJECTIVES Polymorphism in C++ Pointers to derived classes Important point on inheritance Introduction to virtual functions Virtual destructors More about virtual functions

More information

For example, let s say we define an array of char of size six:

For example, let s say we define an array of char of size six: Arrays in C++ An array is a consecutive group of memory locations that all have the same name and the same type. To refer to a particular location, we specify the name and then the positive index into

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 08 Constants and Inline Functions Welcome to module 6 of Programming

More information

Evolution of Programming Languages

Evolution of Programming Languages Evolution of Programming Languages 40's machine level raw binary 50's assembly language names for instructions and addresses very specific to each machine 60's high-level languages: Fortran, Cobol, Algol,

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

12. Pointers Address-of operator (&)

12. Pointers Address-of operator (&) 12. Pointers In earlier chapters, variables have been explained as locations in the computer's memory which can be accessed by their identifer (their name). This way, the program does not need to care

More information

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example

Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example Software Engineering Concepts: Invariants Silently Written & Called Functions Simple Class Example CS 311 Data Structures and Algorithms Lecture Slides Friday, September 11, 2009 continued Glenn G. Chappell

More information

Object-Oriented Principles and Practice / C++

Object-Oriented Principles and Practice / C++ Object-Oriented Principles and Practice / C++ Alice E. Fischer September 26, 2016 OOPP / C++ Lecture 4... 1/33 Global vs. Class Static Parameters Move Semantics OOPP / C++ Lecture 4... 2/33 Global Functions

More information

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED.

THE NAME OF THE CONSTRUCTOR AND DESTRUCTOR(HAVING (~) BEFORE ITS NAME) FUNCTION MUST BE SAME AS THE NAME OF THE CLASS IN WHICH THEY ARE DECLARED. Constructor and Destructor Member Functions Constructor: - Constructor function gets invoked automatically when an object of a class is constructed (declared). Destructor:- A destructor is a automatically

More information

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin

Topics so far. Review. scanf/fscanf. How data is read 1/20/2011. All code handin sare at /afs/andrew/course/15/123/handin 15-123 Effective Programming in C and Unix Announcements SL2 is due Thursday 1/20 midnight Complete the Academic Honesty Form in class All code downloads are from /afs/andrew/course/15/123/download All

More information

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe

OBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++

More information

Pointers, Arrays, and Strings. CS449 Spring 2016

Pointers, Arrays, and Strings. CS449 Spring 2016 Pointers, Arrays, and Strings CS449 Spring 2016 Pointers Pointers are important. Pointers are fun! Pointers Every variable in your program has a memory location. This location can be accessed using & operator.

More information

CS201 Some Important Definitions

CS201 Some Important Definitions CS201 Some Important Definitions For Viva Preparation 1. What is a program? A program is a precise sequence of steps to solve a particular problem. 2. What is a class? We write a C++ program using data

More information

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am

Pointers. Addresses in Memory. Exam 1 on July 18, :00-11:40am Exam 1 on July 18, 2005 10:00-11:40am Pointers Addresses in Memory When a variable is declared, enough memory to hold a value of that type is allocated for it at an unused memory location. This is the

More information

1 of 8 3/28/2010 8:03 AM C++ Special Topics Home Class Info Links Lectures Newsgroup Assignmen This is a short review of special topics in C++ especially helpful for various assignments. These notes are

More information

C++ Programming: Polymorphism

C++ Programming: Polymorphism C++ Programming: Polymorphism 2018 년도 2 학기 Instructor: Young-guk Ha Dept. of Computer Science & Engineering Contents Run-time binding in C++ Abstract base classes Run-time type identification 2 Function

More information

Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

More information

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O

Outline. 1 Function calls and parameter passing. 2 Pointers, arrays, and references. 5 Declarations, scope, and lifetimes 6 I/O Outline EDAF30 Programming in C++ 2. Introduction. More on function calls and types. Sven Gestegård Robertz Computer Science, LTH 2018 1 Function calls and parameter passing 2 Pointers, arrays, and references

More information

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370

Part V. Memory and pointers. Philip Blakely (LSC) C++ Introduction 145 / 370 Part V and pointers Philip Blakely (LSC) C++ Introduction 145 / 370 Outline 19 20 Function pointers 21 Global variables Philip Blakely (LSC) C++ Introduction 146 / 370 Heap and Stack The stack is a Last-In-First-Out

More information

by Pearson Education, Inc. All Rights Reserved.

by Pearson Education, Inc. All Rights Reserved. Let s improve the bubble sort program of Fig. 6.15 to use two functions bubblesort and swap. Function bubblesort sorts the array. It calls function swap (line 51) to exchange the array elements array[j]

More information

Separate Compilation Model

Separate Compilation Model Separate Compilation Model Recall: For a function call to compile, either the function s definition or declaration must appear previously in the same file. Goal: Compile only modules affected by recent

More information

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018 Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Cpt S 122 Data Structures. Introduction to C++ Part II

Cpt S 122 Data Structures. Introduction to C++ Part II Cpt S 122 Data Structures Introduction to C++ Part II Nirmalya Roy School of Electrical Engineering and Computer Science Washington State University Topics Objectives Defining class with a member function

More information

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings 19/10/2017 CE221 Part 2 1 Variables and References 1 In Java a variable of primitive type is associated with a memory location

More information

C Pointers. 6th April 2017 Giulio Picierro

C Pointers. 6th April 2017 Giulio Picierro C Pointers 6th April 07 Giulio Picierro Functions Return type Function name Arguments list Function body int sum(int a, int b) { return a + b; } Return statement (return keyword

More information

Introduction Of Classes ( OOPS )

Introduction Of Classes ( OOPS ) Introduction Of Classes ( OOPS ) Classes (I) A class is an expanded concept of a data structure: instead of holding only data, it can hold both data and functions. An object is an instantiation of a class.

More information

QUIZ. What is wrong with this code that uses default arguments?

QUIZ. What is wrong with this code that uses default arguments? QUIZ What is wrong with this code that uses default arguments? Solution The value of the default argument should be placed in either declaration or definition, not both! QUIZ What is wrong with this code

More information

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

More information

Introducing C++ to Java Programmers

Introducing C++ to Java Programmers Introducing C++ to Java Programmers by Kip Irvine updated 2/27/2003 1 Philosophy of C++ Bjarne Stroustrup invented C++ in the early 1980's at Bell Laboratories First called "C with classes" Design Goals:

More information

Department of Computer science and Engineering Sub. Name: Object oriented programming and data structures Sub. Code: EC6301 Sem/Class: III/II-ECE Staff name: M.Kavipriya Two Mark Questions UNIT-1 1. List

More information

Functions, Pointers, and the Basics of C++ Classes

Functions, Pointers, and the Basics of C++ Classes Functions, Pointers, and the Basics of C++ Classes William E. Skeith III Functions in C++ Vocabulary You should be familiar with all of the following terms already, but if not, you will be after today.

More information

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee

C Language Part 1 Digital Computer Concept and Practice Copyright 2012 by Jaejin Lee C Language Part 1 (Minor modifications by the instructor) References C for Python Programmers, by Carl Burch, 2011. http://www.toves.org/books/cpy/ The C Programming Language. 2nd ed., Kernighan, Brian,

More information

Procedural Programming & Fundamentals of Programming

Procedural Programming & Fundamentals of Programming Procedural Programming & Fundamentals of Programming Lecture 3 - Summer Semester 2018 & Joachim Zumbrägel What we know so far... Data type serves to organize data (in the memory), its possible values,

More information

COMP26120: Pointers in C (2018/19) Lucas Cordeiro

COMP26120: Pointers in C (2018/19) Lucas Cordeiro COMP26120: Pointers in C (2018/19) Lucas Cordeiro lucas.cordeiro@manchester.ac.uk Organisation Lucas Cordeiro (Senior Lecturer, FM Group) lucas.cordeiro@manchester.ac.uk Office: 2.44 Office hours: 10-11

More information

Arrays and Pointers. Overview. Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays

Arrays and Pointers. Overview. Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays Arrays and Pointers Arrays Introducing Pointers C-Style Character Strings Multidimensioned Arrays 1 Overview C++ defines two lower-level compound types: arrays and pointers that are similar to vectors

More information

Where do we go from here?

Where do we go from here? Where do we go from here? C++ classes and objects, with all the moving parts visible operator overloading templates, STL, standards, Java components, collections, generics language and performance comparisons

More information

Pointers! Arizona State University 1

Pointers! Arizona State University 1 Pointers! CSE100 Principles of Programming with C++, Fall 2018 (based off Chapter 10 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions?

Lecture 14. No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Lecture 14 No in-class files today. Homework 7 (due on Wednesday) and Project 3 (due in 10 days) posted. Questions? Friday, February 11 CS 215 Fundamentals of Programming II - Lecture 14 1 Outline Static

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Dynamic Allocation in C

Dynamic Allocation in C Dynamic Allocation in C C Pointers and Arrays 1 The previous examples involved only targets that were declared as local variables. For serious development, we must also be able to create variables dynamically,

More information

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57 Comp 11 Lectures Mike Shah Tufts University June 26, 2017 Mike Shah (Tufts University) Comp 11 Lectures June 26, 2017 1 / 57 Please do not distribute or host these slides without prior permission. Mike

More information

arrays review arrays and memory arrays: character array example cis15 advanced programming techniques, using c++ summer 2008 lecture # V.

arrays review arrays and memory arrays: character array example cis15 advanced programming techniques, using c++ summer 2008 lecture # V. topics: arrays pointers arrays of objects resources: cis15 advanced programming techniques, using c++ summer 2008 lecture # V.1 some of this lecture is covered in parts of Pohl, chapter 3 arrays review

More information

Object Oriented Design

Object Oriented Design Object Oriented Design Chapter 9 Initializing a non-static data member in the class definition is a syntax error 1 9.2 Time Class Case Study In Fig. 9.1, the class definition is enclosed in the following

More information

CS 61c: Great Ideas in Computer Architecture

CS 61c: Great Ideas in Computer Architecture Arrays, Strings, and Some More Pointers June 24, 2014 Review of Last Lecture C Basics Variables, functioss, control flow, types, structs Only 0 and NULL evaluate to false Pointers hold addresses Address

More information

IS0020 Program Design and Software Tools Midterm, Fall, 2004

IS0020 Program Design and Software Tools Midterm, Fall, 2004 IS0020 Program Design and Software Tools Midterm, Fall, 2004 Name: Instruction There are two parts in this test. The first part contains 22 questions worth 40 points you need to get 20 right to get the

More information

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes

Distributed Real-Time Control Systems. Lecture 17 C++ Programming Intro to C++ Objects and Classes Distributed Real-Time Control Systems Lecture 17 C++ Programming Intro to C++ Objects and Classes 1 Bibliography Classical References Covers C++ 11 2 What is C++? A computer language with object oriented

More information

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011 CS 61C: Great Ideas in Computer Architecture (Machine Structures) Introduction to C (Part II) Instructors: Randy H. Katz David A. Patterson http://inst.eecs.berkeley.edu/~cs61c/sp11 Spring 2011 -- Lecture

More information

Introduction to Computer Science Midterm 3 Fall, Points

Introduction to Computer Science Midterm 3 Fall, Points Introduction to Computer Science Fall, 2001 100 Points Notes 1. Tear off this sheet and use it to keep your answers covered at all times. 2. Turn the exam over and write your name next to the staple. Do

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

Today s lecture. Continue exploring C-strings. Pointer mechanics. C arrays. Under the hood: sequence of chars w/ terminating null

Today s lecture. Continue exploring C-strings. Pointer mechanics. C arrays. Under the hood: sequence of chars w/ terminating null Today s lecture Continue exploring C-strings Under the hood: sequence of chars w/ terminating null Review implementation of strcpy, strncpy As abstraction: client of string.h functions Write pig latin

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works

Type Aliases. Examples: using newtype = existingtype; // C++11 typedef existingtype newtype; // equivalent, still works Type Aliases A name may be defined as a synonym for an existing type name. Traditionally, typedef is used for this purpose. In the new standard, an alias declaration can also be used C++11.Thetwoformsareequivalent.

More information

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces Basic memory model Using functions Writing functions Basics Prototypes Parameters Return types Functions and memory Names and namespaces When a program runs it requires main memory (RAM) space for Program

More information

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers

CS 61C: Great Ideas in Computer Architecture. C Arrays, Strings, More Pointers CS 61C: Great Ideas in Computer Architecture C Arrays, Strings, More Pointers Instructor: Justin Hsia 6/20/2012 Summer 2012 Lecture #3 1 Review of Last Lecture C Basics Variables, Functions, Flow Control,

More information

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic

CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic CSCI-1200 Data Structures Fall 2017 Lecture 5 Pointers, Arrays, & Pointer Arithmetic Review from Letctures 3 & 4 C++ class syntax, designing classes, classes vs. structs; Passing comparison functions to

More information

7.1 Optional Parameters

7.1 Optional Parameters Chapter 7: C++ Bells and Whistles A number of C++ features are introduced in this chapter: default parameters, const class members, and operator extensions. 7.1 Optional Parameters Purpose and Rules. Default

More information

Motivation was to facilitate development of systems software, especially OS development.

Motivation was to facilitate development of systems software, especially OS development. A History Lesson C Basics 1 Development of language by Dennis Ritchie at Bell Labs culminated in the C language in 1972. Motivation was to facilitate development of systems software, especially OS development.

More information

2 ADT Programming User-defined abstract data types

2 ADT Programming User-defined abstract data types Preview 2 ADT Programming User-defined abstract data types user-defined data types in C++: classes constructors and destructors const accessor functions, and inline functions special initialization construct

More information

COMP6771 Advanced C++ Programming

COMP6771 Advanced C++ Programming 1.. COMP6771 Advanced C++ Programming Week 5 Part Two: Dynamic Memory Management 2016 www.cse.unsw.edu.au/ cs6771 2.. Revisited 1 #include 2 3 struct X { 4 X() { std::cout

More information

Kurt Schmidt. October 30, 2018

Kurt Schmidt. October 30, 2018 to Structs Dept. of Computer Science, Drexel University October 30, 2018 Array Objectives to Structs Intended audience: Student who has working knowledge of Python To gain some experience with a statically-typed

More information

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010

CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011. MIDTERM EXAMINATION Spring 2010 CS201- Introduction to Programming Latest Solved Mcqs from Midterm Papers May 07,2011 Lectures 1-22 Moaaz Siddiq Asad Ali Latest Mcqs MIDTERM EXAMINATION Spring 2010 Question No: 1 ( Marks: 1 ) - Please

More information

Padasalai.Net s Model Question Paper

Padasalai.Net s Model Question Paper Padasalai.Net s Model Question Paper STD: XII VOLUME - 2 MARKS: 150 SUB: COMPUTER SCIENCE TIME: 3 HRS PART I Choose the correct answer: 75 X 1 = 75 1. Which of the following is an object oriented programming

More information

Week 8: Operator overloading

Week 8: Operator overloading Due to various disruptions, we did not get through all the material in the slides below. CS319: Scientific Computing (with C++) Week 8: Operator overloading 1 The copy constructor 2 Operator Overloading

More information

Pointers II. Class 31

Pointers II. Class 31 Pointers II Class 31 Compile Time all of the variables we have seen so far have been declared at compile time they are written into the program code you can see by looking at the program how many variables

More information

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction CS106L Spring 2009 Handout #21 May 12, 2009 static Introduction Most of the time, you'll design classes so that any two instances of that class are independent. That is, if you have two objects one and

More information

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects

Vectors of Pointers to Objects. Vectors of Objects. Vectors of unique ptrs C++11. Arrays of Objects Vectors of Objects As we have mentioned earlier, you should almost always use vectors instead of arrays. If you need to keep track of persons (objects of class Person), you must decide what to store in

More information

Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition. Chapter 7 Basic Semantics Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

More information

... IntArray B (100); // IntArray with 100 elements, each initialized to 0

... IntArray B (100); // IntArray with 100 elements, each initialized to 0 Types with External Resources A class constructor is invoked when an object comes into scope. The constructor prepares the object by creating an environment in which the member functions operate. For many

More information

(Refer Slide Time: 4:00)

(Refer Slide Time: 4:00) Principles of Programming Languages Dr. S. Arun Kumar Department of Computer Science & Engineering Indian Institute of Technology, Delhi Lecture - 38 Meanings Let us look at abstracts namely functional

More information

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors

POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors POLYMORPHISM 2 PART Abstract Classes Static and Dynamic Casting Common Programming Errors CSC 330 OO Software Design 1 Abstract Base Classes class B { // base class virtual void m( ) =0; // pure virtual

More information

CS102: Variables and Expressions

CS102: Variables and Expressions CS102: Variables and Expressions The topic of variables is one of the most important in C or any other high-level programming language. We will start with a simple example: int x; printf("the value of

More information

CSC1322 Object-Oriented Programming Concepts

CSC1322 Object-Oriented Programming Concepts CSC1322 Object-Oriented Programming Concepts Instructor: Yukong Zhang February 18, 2016 Fundamental Concepts: The following is a summary of the fundamental concepts of object-oriented programming in C++.

More information