C programming program design including data structures second edition
This presentation is the property of its rightful owner.
Sponsored Links
1 / 122

C++ Programming: Program Design Including Data Structures, Second Edition PowerPoint PPT Presentation


  • 68 Views
  • Uploaded on
  • Presentation posted in: General

C++ Programming: Program Design Including Data Structures, Second Edition. Chapter 13: Pointers, Classes, Lists, and Virtual Functions. Objectives. In this chapter you will: Learn about the pointer data type and pointer variables Explore how to declare and manipulate pointer variables

Download Presentation

C++ Programming: Program Design Including Data Structures, Second Edition

An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


C programming program design including data structures second edition

C++ Programming:Program Design Including Data Structures, Second Edition

Chapter 13: Pointers, Classes, Lists, and Virtual Functions


Objectives

Objectives

In this chapter you will:

  • Learn about the pointer data type and pointer variables

  • Explore how to declare and manipulate pointer variables

  • Learn about the address of operator and the dereferencing operator

  • Discover dynamic variables

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Objectives1

Objectives

  • Explore how to use the newanddeleteoperators to manipulate dynamic variables

  • Learn about pointer arithmetic

  • Discover dynamic arrays

  • Become aware of theshallow and deep copies of data

  • Discover the peculiarities of classes with pointer data members

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Objectives2

Objectives

  • Explore how dynamic arrays are used to process lists

  • Learn about virtual functions

  • Examine the relationship between the address of operator and classes

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Pointer variables

Pointer Variables

  • Pointer variable: the content is a memory address

  • Declaring Pointer Variables:

    dataType *identifier;

    int *p;

    char *ch;

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Pointer variables continued

Pointer Variables (continued)

  • These statements are equivalent

    • int *p;

    • int* p;

    • int * p;

    • The character * can appear anywhere between type name and variable name

      int* p, q;

  • Only p is the pointer variable, not q

    • Here q is an int variable

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Pointer variables continued1

Pointer Variables (continued)

  • To avoid confusion, attach the character * to the variable name

    int *p, q;

  • The following statement declares both p and q to be pointer variables of the type int

    int *p, *q;

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Recall that

6000

‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

str [0] [1] [2] [3] [4] [5] [6] [7]

Recall that . . .

char str [ 8 ];

stris thebase addressof the array. We say str is a pointerbecause its value is an address.

  • It is a pointer constant because the value of str itself cannot be changed by assignment. It “points” to the memory location of a char.

expanded by J. Goetz, 2004


Addresses in memory

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 address of the variable

    int x;

    float number;

    char ch;

    2000 2002 2006

x number ch

expanded by J. Goetz, 2004


Address of operator

Address Of Operator (&)

  • The ampersand, &, is called the address of operator

  • Address of operator: unary operator that returns the address of its operand

    int x;

    int *p;

    p = &x; // returns the address of x, store the address of x in p

    // x and value of p refer to the same memory location

C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


Obtaining memory addresses

Obtaining Memory Addresses

  • the address of a non-array variable can be obtained by using theaddress-of operator &

    int x;

    float number;

    char ch;

    cout << “Address of x is “ << &x << endl;

    cout << “Address of number is “ << &number << endl;

    cout << “Address of ch is “ << &ch << endl;

expanded by J. Goetz, 2004


What is a pointer variable

What is a pointer variable?

  • A pointer variableis a variablewhosevalue is the addressof a location in memory.

  • to declarea pointer variable, you must specifythe type of value that the pointer will point to, for example,

    int* ptr; // ptr will hold the address of an int

    char* q;// q will hold the address of a char

    enum ColorType {RED, GREEN, BLUE};

    ColorType color;

    ColorType* colorPtr;

expanded by J. Goetz, 2004


Using a pointer variable

Using a Pointer Variable

2000

12

x

3000

2000

ptr

int x;

x = 12;

int* ptr;

ptr = &x;

NOTE: Because ptr holds the address of x,

we say that ptr “points to” x

enum ColorType {RED, GREEN, BLUE};

ColorType color;

ColorType* colorPtr = &color ;

expanded by J. Goetz, 2004


Dereferencing operator

Dereferencing Operator (*)

  • C++ uses * as

    • the binary multiplication operator and

    • as a unary operator

  • When used as a unary operator, *

    • Called the dereferencing operator or indirection operator

  • Refers to the object to which its operand (that is, a pointer) points

  • C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Dereferencing operator1

    Dereferencing Operator (*)

    int x = 25;

    int *p;

    p = &x; // store the address of x in p

    count << *p << endl; // prints 25

    • *p refers to the object to whicha pointer ppoints

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Unary operator is the indirection dereference operator

    Unary operator * is the indirection (dereference) operator

    2000

    *ptr 12

    x

    3000

    2000

    ptr

    int x;

    x = 12;

    int* ptr;

    ptr = &x;

    cout << *ptr;

    NOTE:The valuepointed to byptr is denoted by *ptr

    expanded by J. Goetz, 2004


    Using the dereference operator

    Using the Dereference Operator

    int x;

    x = 12;

    int* ptr;

    ptr = &x;

    *ptr = 5; // changes the value // at address ptr to 5

    2000

    12 5

    x

    3000

    2000

    ptr

    expanded by J. Goetz, 2004


    Another example

    Another Example

    4000

    *q A Z

    ch

    5000 6000

    4000 4000

    q p

    char ch;

    ch = ‘A’;

    char* q;

    q = &ch;

    *q = ‘Z’;

    char* p;

    p = q; // the &ch has value 4000

    // now p and q both point to ch

    expanded by J. Goetz, 2004


    Using a pointer to access the elements of a string

    Using a Pointer to Access the Elements of a String

    3000

    char msg[ ] = “Hello”; ‘M’ ‘a’

    3001

    char* ptr; 3000

    ptr = msg; // recall that msg == &msg[ 0 ]

    *ptr = ‘M’ ;

    ptr++;// increments the address in ptr

    *ptr = ‘a’;

    ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

    ptr

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    int StringLength ( /* in */ const char str[ ] )

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    // Precondition: str is a null-terminated string

    // Postcondition: FCTVAL == length of str (not counting ‘\0’)

    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

    {

    char* p ;

    int count = 0;

    p = str;

    while ( *p != ‘\0’ ) {

    count++ ;

    p++ ; // increments the address p by sizeof char

    }

    return count;

    }

    20

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    floating

    address

    float double long double

    pointer reference

    C++ Data Types

    simple

    structured

    integral enum

    array struct union class

    char short int long bool

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Classes structs and pointer variables

    Classes, structs, and Pointer Variables

    • Pointers can be declared to classes and structs

    • To simplify the accessing of class orstructcomponents via a pointer,

      • C++ provides the member access operator arrow, ->

    • The syntax for accessing a class (struct) member using the operator -> is:

      pointerVariableName->classMemberName

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Using a pointer to access the elements

    Using a Pointer to Access the Elements

    Syntax:

    • PointerVariable -> MemberName

      or

    • (* PointerVariable).MemberName

    • TimeType startTime(8, 30, 0);

      TimeType* timePtr;

      (*timePtr).Increment(); // or

      timePtr ->Increment();

    • TimeType* myArray[20]

      (*myArray[4] ).Increment(); // or

      myArray[4]->Increment();

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Some c pointer operations

    Some C++ Pointer Operations

    Precedence

    Higher->Select member of class pointed to

    Unary: ++ -- ! * new delete

    Increment, Decrement, NOT, Dereference, Allocate, Deallocate

    + - Add Subtract

    < <= > >= Relational operators

    == != Tests for equality, inequality

    Lower = Assignment

    24

    expanded by J. Goetz, 2004


    Initializing pointer variables

    Initializing Pointer Variables

    • C++ does not automatically initialize variables

    • Pointer variables can be initialized using the constant value 0, called the “null pointer” denoted byNULLin header file cstddef p.1474.

      The following two statements are equivalent:p = NULL; // predefined constant

      p = 0;

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Initializing pointer variables1

    Initializing Pointer Variables

    NOTE: It is an error to dereference a pointer whose value is NULL.

    • Such an error may cause your program to crash, or behave erratically.

    • It is the programmer’s job to check for this.

      while (ptr != NULL) {

      . . .// ok to use *ptr here

      }

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    3 kinds of program data

    3 Kinds of Program Data

    • STATIC DATA:memory allocation exists throughout execution of program

      static long currentSeed;

    • AUTOMATIC DATA:automatically created at function entry, resides in activation frame of the function, and is destroyed when returning from function

    • DYNAMIC DATA: explicitly allocated and deallocated during program execution by C++ instructions written by programmer using operators new and delete

    expanded by J. Goetz, 2004


    Allocation of memory

    Allocation of Memory

    STATIC

    ALLOCATION

    Static allocation is the allocation of memory space at compile time.

    DYNAMIC

    ALLOCATION

    Dynamic allocation is the allocation of memory space at run time by using operator new.

    expanded by J. Goetz, 2004


    Dynamic variables

    Dynamic Variables

    • Dynamic variables: created during execution

      • using pointers

  • Two operators, new and delete,

    • to create and destroy dynamic variables

  • new and delete are reserved words

  • C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Operator new

    Operator new

    • The syntax for new:

      new dataType; //to allocate a single variable

      e.g. p = newint;

      new dataType [intExp]; //to allocate an array of variables

      e.g. p = newchar[5];

      where intExp is any expression evaluating to a positive integer

    • If memory is available, in an area called the heap (or free store)

      newallocates memory of the designated type and returns a pointer to it.

    • Otherwise, program terminates with error message.

      • Allocated memory is uninitialized

    • The dynamically allocated object exists until the delete operator destroys it.

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Dynamically allocated data

    Dynamically Allocated Data

    2000

    ptr

    char* ptr;

    ptr = new char;

    *ptr = ‘B’;

    cout << *ptr;

    expanded by J. Goetz, 2004


    Dynamically allocated data p 710

    Dynamically Allocated Data p.710

    2000

    ptr

    char* ptr;

    ptr = new char;

    *ptr = ‘B’;

    cout << *ptr;

    NOTE: The statement stores the address of the allocated memory in ptr

    expanded by J. Goetz, 2004


    Dynamically allocated data1

    Dynamically Allocated Data

    2000

    ptr

    ‘B’

    char* ptr;

    ptr = new char;

    *ptr = ‘B’;

    cout << *ptr;

    NOTE: Dynamic data has no variable name

    expanded by J. Goetz, 2004


    Dynamically allocated data2

    Dynamically Allocated Data

    2000

    ptr

    NOTE: the delete operator 1.deallocates the memory pointed to by ptr and

    2. pointed- to variable *ptr is deleted (dynamic data is deleted)

    char* ptr;

    ptr = new char;

    *ptr = ‘B’;

    cout << *ptr;

    delete ptr;

    ?

    expanded by J. Goetz, 2004


    Operator delete

    Operator delete

    • deletedestroys dynamic variables

    • The syntax of delete has two forms (statements):

      delete pointer; //to destroy a single dynamic variable

      delete [] pointer; //to destroy a dynamically //created array

    • Operator delete returnsto thefree store memory which was previously allocated at run-time by operator new

      • it deletes the pointed-to variable (dereferenced variable)

    • The object or array currently pointed to by the pointer is deallocated, and the pointer is considered unassigned (undefined).

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Operator delete1

    Operator delete

    • The syntax of delete has two forms (statements):

      delete pointer; //to destroy a single dynamic variable

      delete [] pointer; //to destroy a dynamically //created array

    • The statements

      delete p;

      delete [] name;

      deallocate memory referenced by the pointers p and name

    • Square brackets are used with delete to deallocate a dynamically allocated array.

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    What happens here

    What happens here?

    3

    ptr

    int* ptr = new int;

    *ptr = 3;

    ptr = new int; // changes value of ptr

    *ptr = 4; // here the 3 becomes inaccessible

    3

    ptr

    4

    expanded by J. Goetz, 2004


    Inaccessible object

    Inaccessible Object

    • An inaccessible object is an unnamed object that was created by operator new and which a programmer has left without a pointer to it.

      int* ptr = new int;

      *ptr = 8;

      int* ptr2 = new int;

      *ptr2 = -5;

      How else can an object become inaccessible?

    8

    ptr

    -5

    ptr2

    expanded by J. Goetz, 2004


    Making an object inaccessible

    Making an Object Inaccessible

    8

    ptr

    -5

    ptr2

    int* ptr = new int;

    *ptr = 8;

    int* ptr2 = new int;

    *ptr2 = -5;

    ptr = ptr2;// here the 8 becomes inaccessible

    8

    ptr

    -5

    ptr2

    expanded by J. Goetz, 2004


    Memory leak

    Memory Leak

    • A memory leak is the loss of available memory space

      • that occurs when dynamic data is allocatedbutnever deallocated.

    expanded by J. Goetz, 2004


    A dangling pointer

    A Dangling Pointer

    • is a pointer that points to dynamic memory that has been deallocated

      int* ptr = new int;

      *ptr = 8;

      int* ptr2 = new int;

      *ptr2 = -5;

      ptr = ptr2;

    8

    ptr

    -5

    ptr2

    FOR EXAMPLE,

    expanded by J. Goetz, 2004


    Leaving a dangling pointer

    Leaving a Dangling Pointer

    8

    ptr

    -5

    ptr2

    int* ptr = new int;

    *ptr = 8;

    int* ptr2 = new int;

    *ptr2 = -5;

    ptr = ptr2;// here the 8 becomes inaccessible

    delete ptr2;

    // ptr is left dangling !!!

    ptr2 = NULL;

    8

    ptr

    NULL

    ptr2

    expanded by J. Goetz, 2004


    Operations on pointer variables

    Operations on Pointer Variables

    • Assignment: value of one pointer variable can be assigned to another pointer of same type

    • Relational operations: two pointer variables of same type can be compared for equality, etc.

    • Some limited arithmetic operations:

      • Integervalues can be added and subtracted from a pointer variable

      • Value of one pointer variable can be subtracted from another pointer variable

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Some c pointer operations1

    Some C++ Pointer Operations

    • int arr[10];

      int* ptr;

      the assignmentstatement

      ptr = arr;

      has the effect as

      ptr = &arr[0];

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Some c pointer operations2

    Some C++ Pointer Operations

    • The logical NOT operator can be used to test the null pointer:

      if (!ptr) //in spite of ptr is a pointer expression, not a Boolean expression

      DoSomething();

    • The same but preferable:

      if (ptr == NULL)

      DoSomething();

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Some c pointer operations3

    Some C++ Pointer Operations

    • To testpointers:

      int *intPtr1, *intPtr2;

      if (intPtr1 == intPtr2)

    • To test the integers that intPtr1, intPtr2 point to:

      if (*intPtr1 == *intPtr2)

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Operations on pointer variables1

    Operations on Pointer Variables

    • When an integer is added to a pointer variable

      • Value of pointer is incremented by integer times the size of the memory that the pointer points to

        • If ptr points some element of an array (int array[]), then ptr + 7 points the array element that is seventhbeyond the one currently pointed to by ptr (regardless of the size in bytes of each array element)

  • When an integer is subtracted from a pointer variable

    • Value of pointer variable is decremented by the integer times the size of the memory to which the pointer is pointing

  • C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Dynamic arrays

    Dynamic Arrays

    • Dynamic array: array created during execution

    • Use the second form of the new operator to create a dynamic array

    • The statement

    • p = new int[10];

      • allocates 10 contiguous memory locations, each of the type int, and storesthe address of the first memory location into p

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Dynamic array allocation

    Dynamic Array Allocation

    char *ptr;// ptr is a pointer variable that

    // can hold the address of a char

    ptr = new char[ 5 ];

    // dynamically, during run time, allocates

    // memory for a 5 character array

    // and stores the base address into ptr

    6000

    6000

    ptr

    expanded by J. Goetz, 2004


    Dynamic array allocation1

    Dynamic Array Allocation

    char *ptr ;

    ptr = new char[ 5 ];

    strcpy( ptr, “Bye” );

    ptr[ 1 ] = ‘u’; // a pointer can be subscripted

    or ptr++; *ptr = ‘u’;

    cout << ptr[ 2] ;

    ‘u’

    6000

    ‘B’ ‘y’ ‘e’ ‘\0’

    ptr

    6000

    expanded by J. Goetz, 2004


    Recall that1

    6000

    ‘H’ ‘e’ ‘l’ ‘l’ ‘o’ ‘\0’

    list [0] [1] [2] [3] [4] [5] [6] [7]

    Recall that . . .

    char list [ 8 ];

    stris thebase addressof the array. We say list is a pointerbecause its value is an address.

    • It is a pointer constant because the value of list itself cannot be changed by assignment – list++. It “points” to the memory location of a list.

    expanded by J. Goetz, 2004


    Dynamic array deallocation

    Dynamic Array Deallocation

    char *ptr ;

    ptr = new char[ 5 ];

    strcpy( ptr, “Bye” );

    ptr[ 1 ] = ‘u’;

    delete ptr;// deallocates array pointed to by ptr

    // ptr itself isnot deallocated

    // the value ofptrisundefined.

    ?

    ptr

    expanded by J. Goetz, 2004


    Dynamic array allocation created by user

    Dynamic Array Allocation created by user

    int *intList;

    int arraySize;

    cout << “Enter the array size”;

    cin >> arraySize;

    cout << endl;

    intList = new int [arraySize];

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Functions and pointers

    Functions and Pointers

    • A pointer variable can be passed as a parameter either by value or by reference

    • To make a pointer a reference parameter in a function heading, * appears before the & between the data type name and the identifier

      void example(int*&p, double *q)

      { ….}

      // Both p and q are pointers

    • A function can return a value of type pointer

      int* example (int* &p, double *q)

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Shallow vs deep copy and pointers

    Shallow vs Deep Copy and Pointers

    • In a shallow copy, two or more pointers of the same type point to the same memory (the same data)

      int *first;

      int *second;

      first = new int[10]; // suppose that it is filled out

      second = first; // shallow copy,

    to same data

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Shallow vs deep copy and pointers1

    Shallow vs Deep Copy and Pointers

    • In a deep copy, two or more pointers have their own data

      int *first;

      int *second;

      first = new int[10]; // suppose that it is filled out

      second = new int[10];

      for (int j = 0; j < 10; j++)

      second [j] = first [j]; // it produces a deep copy,

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Classes and pointers some peculiarities

    Classes and Pointers: Some Peculiarities

    We’ll use:

    pointerDataClass objectOne;

    pointerDataClass objectTwo;

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Destructor

    Destructor

    • Suppose that during program execution the pointer p creates a dynamic array

    • When objectOne goes out of scope, all the data members of objectOne are destroyed

    • If pointer p does not use the delete operator to deallocate a dynamic array

      • Memory of the dynamic arraystays marked as allocated, even though it is inaccessible

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Destructor continued

    Destructor (continued)

    • Destructor automaticallyexecutes whenever a class object goes out of scope

    • Put code in the destructor to ensure that

      • when objectOne goes out of scope, the memory created by pointer p is deallocated

        pointerDataClass:: ~pointerDataClass()

        { delete [ ] p; }

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Assignment operator

    Assignment Operator

    objectTwo = objectOne; // shallow copy

    • To avoid shallow copying of data for classes with a pointer data member, overload the assignment operator =>ch.14

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    objectTwo = objectOne; // shallow copy

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    • Once overloaded, both the objects objectOne and objectTwo have their own data

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Copy constructor

    Copy Constructor

    • Consider the following statement:

      pointerDataClass objectThree(objectOne);

    • objectThree is being declared and initialized using the value of objectOne

      • Called default member-wise initialization

      • Initialization due to constructor, called copy constructor provided by the compiler

      • This default initialization would lead to a shallow copying of the data

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Copy constructor continued

    Copy Constructor (continued)

    • If a class has pointer data members:

      • During object declaration, initialization of one object using the value of another object leads to shallow copying of data

      • If an object is passed by value and the default member-wise copying of data is allowed, it would lead to shallow copying of data

    • In both cases, must override the definition of the copy constructor provided by the compiler

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Copy constructor continued1

    Copy Constructor (continued)

    • Add a statement that includes the copy constructor in the definition of the class, and then write its definition

    • For the class pointerDataClass, you can overcome shallow copying of data by including the copy constructor

      • when there is a copy constructor provided for a class, the copy constructor is used to make copies for pass by value

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Copy constructor continued2

    Copy Constructor (continued)

    • The general syntax to include the copy constructor in the definition of a class is:

      className(const className& otherObject);

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    // SPECIFICATION FILE (dynarray.h)

    // Safe integer array class allows 1.run-time //specification of size, 2. prevents indexes from going //out of bounds, 3. allows aggregate array copying and //initialization.

    class DynArray {

    public:

    DynArray( /* in */ int arrSize );

    // Constructor.

    // PRE: arrSize is assigned

    // POST: IF arrSize >= 1 && enough memory THEN

    // Array of size arrSize is created with // all elements == 0 ELSE error message.

    DynArray( const DynArray& otherArr );

    // Copy constructor.

    // POST: this DynArray is a deep copy of otherArr

    // Is implicitly called for initialization.

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    // SPECIFICATION FILE continued (dynarray.h)

    ~DynArray( );

    // Destructor.

    // POST: Memory for dynamic array deallocated.

    int ValueAt ( /* in */ int i ) const;

    // PRE: i is assigned.

    // POST: IF 0 <= i < size of this array THEN

    // FCTVAL == value of array element at index i

    // ELSE error message.

    void Store ( /* in */ int val, /* in */ int i )

    // PRE: val and i are assigned

    // POST: IF 0 <= i < size of this array THEN

    // val is stored in array element i

    // ELSE error message.

    68

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    // SPECIFICATION FILE continued (dynarray.h)

    void CopyFrom ( /* in */ DynArray otherArr);

    // POST: IF enough memory THEN

    // new array created (as deep copy)

    // with size and contents

    // same as otherArr

    // ELSE error message.

    private:

    int* arr ;

    int size ;

    };

    69

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    class DynArray

    Free store

    6000

    DynArray

    80

    40

    90

    0

    0

    Private data:

    size5

    arr6000

    ~DynArray

    DynArray

    ValueAt

    Store

    CopyFrom

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    DynArray::DynArray( /* in */ int arrSize )

    // Constructor.

    // PRE: arrSize is assigned

    // POST: IF arrSize >= 1 && enough memory THEN

    // Array of size arrSize is created with

    // all elements == 0 ELSE error message.

    {

    int i;

    if ( arrSize < 1 ) {

    cerr << “DynArray constructor - invalid size: “

    << arrSize << endl;

    exit(1);

    }

    arr = new int[arrSize] ; // allocate memory pointed by arr

    size = arrSize;

    for (i = 0; i < size; i++)

    arr[i] = 0;

    }

    71

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    DynArray beta(5); //constructor

    beta

    Free store

    2000

    DynArray

    0

    0

    0

    0

    0

    Private data:

    size5

    arr 2000

    ~DynArray

    DynArray

    ValueAt

    Store

    CopyFrom

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    beta.Store(75, 2);

    beta

    Free store

    2000

    DynArray

    0

    0

    75

    0

    0

    Private data:

    size 5

    arr 2000

    ~DynArray

    DynArray

    ValueAt

    Store

    CopyFrom

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    void DynArray::Store ( /* in */ int val, /* in */ int i )

    // PRE: val and i are assigned

    // POST: IF 0 <= i < size of this array THEN

    // arr[i] == val

    // ELSE error message.

    {

    if ( i < 0 || i >= size ) {

    cerr << “Store - invalid index : “ << i << endl;

    exit(1) ;

    }

    arr[i] = val ;

    }

    74

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    DynArray gamma(4);//constructor

    gamma beta

    3000

    2000

    DynArray

    DynArray

    0

    0

    0

    0

    0

    0

    75

    0

    0

    Private:

    size 4

    arr 3000

    Private:

    size 5

    arr 2000

    ~DynArray

    ~DynArray

    DynArray

    DynArray

    ValueAt

    ValueAt

    Store

    Store

    CopyFrom

    CopyFrom

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    gamma.Store(-8,2);

    gamma beta

    3000

    2000

    DynArray

    DynArray

    0

    0

    -8

    0

    0

    0

    75

    0

    0

    Private:

    size 4

    arr 3000

    Private:

    size 5

    arr 2000

    ~DynArray

    ~DynArray

    DynArray

    DynArray

    ValueAt

    ValueAt

    Store

    Store

    CopyFrom

    CopyFrom

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    int DynArray::ValueAt ( /* in */ int i ) const

    // PRE: i is assigned.

    // POST: IF 0 <= i < size THEN

    // FCTVAL == arr[i]

    // ELSE halt with error message.

    {

    if ( i < 0 || i >= size ) {

    cerr << “ValueAt - invalid index : “ << i << endl;

    exit(1) ;

    }

    return arr[i];

    }

    77

    expanded by J. Goetz, 2004


    Why is a destructor needed

    Why is a destructor needed?

    • When a DynArray class variable goes out of scope, the memory space for data members size and pointerarr is deallocated.

    • But the dynamic array that arr points to is not automatically deallocated.

    • A class destructor is used to deallocate the dynamic memory pointed to by the data member.

    expanded by J. Goetz, 2004


    Class dynarray destructor

    class DynArray Destructor

    DynArray::~DynArray( );

    // Destructor.

    // POST: Memory for dynamic array deallocated.

    {

    delete [ ] arr ;

    }

    79

    expanded by J. Goetz, 2004


    What happens

    What happens . . .

    • When a function is called that uses pass by value for a class object of DynArray type?

    beta

    2000

    DynArray

    0

    0

    75

    0

    0

    Private:

    size 5

    arr 2000

    ~DynArray

    DynArray

    ValueAt

    Store

    CopyFrom

    expanded by J. Goetz, 2004


    Passing a class object by value

    Passing a Class Object by Value

    int main()

    {

    DynArray beta(5);

    SomeFunc(beta);

    }

    void SomeFunc( DynArray someArr )

    // uses pass by value, someArr is a shallow copy,

    // their arr pointers point to the same dynamic array, so //this function can corrupt the dynamic

    //array used by class object beta

    {

    }

    81

    expanded by J. Goetz, 2004


    By default pass by value makes a shallow copy

    By default,Pass-by-value makes a shallow copy

    DynArray beta(5); // CLIENT CODE

    .

    .

    .

    SomeFunc( beta ); // function call

    beta someArr

    2000

    DynArray

    .

    .

    .

    DynArray

    .

    .

    .

    0

    0

    75

    0

    0

    Private:

    size 5

    arr 2000

    Private:

    size 5

    arr 2000

    shallow copy

    expanded by J. Goetz, 2004


    Shallow copy vs deep copy

    Shallow Copyvs.Deep Copy

    • a shallow copycopies only the class data members, and does not make a copy ofanypointed-to data

    • a deep copycopies not only the class data members, but also makes a separate stored copy of any pointed-to data

    expanded by J. Goetz, 2004


    What s the difference

    What’s the difference?

    • a shallow copysharesthe pointed to dynamic data with the original class object

    • a deep copymakes its own copy of thepointed to dynamic dataat different locations than the original class object

    expanded by J. Goetz, 2004


    Making a separate deep copy

    Making a (Separate) Deep Copy

    beta

    someArr

    2000

    DynArray

    .

    .

    .

    0

    0

    75

    0

    0

    Private:

    size 5

    arr 2000

    4000

    DynArray

    .

    .

    .

    0

    0

    75

    0

    0

    Private:

    size 5

    arr 4000

    deep copy

    expanded by J. Goetz, 2004


    Initialization of class objects

    Initialization of Class Objects

    • C++ defines initialization to mean the following

      • initialization in a variable declaration

        DynArray beta = someArr; // member by member copy

      • passing an object argument by value

      • returning an object as the return value of a functionreturn someObject;

    • by default, C++ uses shallow copies for these initializations

    expanded by J. Goetz, 2004


    Initialization of class objects1

    Initialization of Class Objects

    • when a class has a data member pointer to dynamically allocated data, you should writewhat is called acopy constructor

    • the copy constructor isimplicitlycalled in initialization situationsandmakes a deep copy of the dynamic data in a different memory location

    expanded by J. Goetz, 2004


    More about copy constructors

    More about Copy Constructors

    • when there is a copy constructor provided for a class, the copy constructor is usedto make copiesfor pass by value

    • you do not call the copy constructor

    • like other constructors, it has no return type

    • because the copy constructor properly defines pass by value for your class, it must use pass by reference in its definition with const

    expanded by J. Goetz, 2004


    Copy constructor1

    Copy Constructor

    • copy constructor is a special member function of a class that is implicitly automatically called in these 3 situations:

      • initializing an object variable in its declaration

      • passing object parametersby value

      • returning an object as thereturn value of a function

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    SomeFunc(beta);// copy-constructor

    // beta passed by value

    beta someArr

    2000

    4000

    DynArray

    DynArray

    0

    0

    75

    0

    0

    0

    0

    75

    0

    0

    Private:

    size 5

    arr 2000

    Private:

    size 5

    arr 4000

    ~DynArray

    ~DynArray

    DynArray

    DynArray

    ValueAt

    ValueAt

    Store

    Store

    CopyFrom

    CopyFrom

    DEEP COPY

    expanded by J. Goetz, 2004


    Suppose somefunc calls store

    SupposeSomeFunccalls Store

    // FUNCTION CODE

    void SomeFunc( DynArray someArr )

    // Uses pass by value

    {

    someArr.Store(290, 2);

    .

    .

    .

    }

    WHAT HAPPENS IN THE SHALLOW COPY SCENARIO?

    91

    expanded by J. Goetz, 2004


    Beta arr 2 has changed

    beta.arr[2] has changed

    DynArray beta(5); // CLIENT CODE

    .

    .

    .

    SomeFunc( beta);

    beta someArr

    2000

    DynArray

    .

    .

    .

    DynArray

    .

    .

    .

    0

    0

    290

    0

    0

    Private:

    size 5

    arr 2000

    Private:

    size 5

    arr 2000

    shallow copy

    expanded by J. Goetz, 2004


    Beta arr 2 has changed1

    beta.arr[2] has changed

    NOTICE THAT NOT JUST FOR THE SHALLOW COPY,

    BUT ALSO FOR ARGUMENT beta,

    THE DYNAMIC DATA HAS CHANGED!

    beta someArr

    2000

    DynArray

    .

    .

    .

    DynArray

    .

    .

    .

    0

    0

    290

    0

    0

    Private:

    size 5

    arr 2000

    Private:

    size 5

    arr 2000

    shallow copy

    expanded by J. Goetz, 2004


    Classes with data member pointers need

    Classes with Data Member Pointers Need

    CONSTRUCTOR

    COPY CONSTRUCTOR

    DESTRUCTOR

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    DynArray::DynArray( const DynArray& otherArr )

    // Copy constructor

    // Implicitly called for deep copy in initializations.

    // POST:If room on free store THEN

    // new array of size otherArr.size is created

    // on free store && arr == its base address

    // && size == otherArr.size

    // && arr[0..size-1] == otherArr.arr[0..size-1]

    // ELSE error message.

    {

    int i ;

    size = otherArr.size ;

    arr = new int[size] ; //!!! allocate memory for copy

    // arr hasn’t exist so far

    for ( i = 0; i< size ; i++ )

    arr[i] = otherArr.arr[i] ; // copies array

    }

    // the copy constructor is creating a new class object that doesn’t

    // already exist.

    95

    expanded by J. Goetz, 2004


    What about the assignment operator

    What about the assignment operator?

    • the default method used for assignment of class objects makes a shallow copy

    • if your class has a data member pointer to dynamic data, you should write a member function to create a deep copy of the dynamic data

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    gamma.CopyFrom(beta);

    gamma beta

    3000

    2000

    DynArray

    DynArray

    ?

    ?

    75

    ?

    ?

    ?

    ?

    75

    ?

    ?

    Private:

    size 5

    arr 3000

    Private:

    size 5

    arr 2000

    ~DynArray

    ~DynArray

    DynArray

    DynArray

    ValueAt

    ValueAt

    Store

    Store

    CopyFrom

    CopyFrom

    DEEP COPY

    expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    void DynArray::CopyFrom ( /* in */DynArray otherArr )

    // Creates a deep copy of otherArr.

    // POST: Array pointed to by [email protected] deallocated

    // && IF room on free store

    // THEN new array is created on free store

    // && arr == its base address

    // && size == otherArr.size

    // && arr[0..size-1] == otherArr[0..size-1]

    // ELSE halts with error message.

    {

    int i ;

    delete [ ] arr ;//!!! delete current array

    // next the same as a copy constructor

    size = otherArr.size ;

    arr = new int [size] ;//!!! allocate new array

    for ( i = 0; i< size ; i++ ) // deep copy array

    arr[i] = otherArr.arr[i] ;

    }

    98

    expanded by J. Goetz, 2004


    Array based lists

    Array-Based Lists

    • List: a homogeneous collection of elements

    • List length: number of elements in the list

    • Operations performed on a list are:

      • Create the list andinitialize to an empty state

      • Determine whether the list is empty

      • Determine whether the list is full

      • Find the size of the list

      • Destroy, or clear the list

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Array based lists continued

    Array-Based Lists (continued)

    • Operations performed on a list are:

      • Determine whether an item is the same as a given list element

      • Insert an item in the list at the specified location

      • Remove an item from the list at the specified location

      • Replace an item at the specified location with another item

      • Retrieve an item from the list at the specified location

      • Search the list for a given item

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Array based lists continued1

    Array-Based Lists (continued)

    • Can create dynamic arrays, which permit user to specify the size of the array

    • We need 3 variables to maintain and process array-based list:

      • list: the array holding the list elements

      • length: the length of the list (#items in list)

      • maxSize: the maximum size of the array

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    void insertEnd(int insertItem);

    //Function to insert an item at the end of the list

    //The parameter insertItem specifies the item to be

    //inserted.

    //Postcondition: list[length] = insertItem; and length++;

    // If the list is full, an appropriate

    // message is displayed.

    void removeAt(int location);

    //Function to remove the item from the list at the

    //position specified by location

    //Postcondition: The list element at list[location] is

    // removed and length is decremented by 1.

    // If location is out of range, an appropriate message

    // is displayed.

    void retrieveAt(int location, int& retItem);

    //Function to retrieve the element from the list at the

    //position specified by location

    //Postcondition: retItem = list[location]

    // If location is out of range, an appropriate

    // message is displayed.

    void replaceAt(int location, int repItem);

    //Function to replace the elements in the list at the

    //position specified by location. The item to be replaced

    //is specified by the parameter repItem.

    //Postcondition: list[location] = repItem

    // If location is out of range, an appropriate

    // message is displayed.

    void clearList();

    //Function to remove all the elements from the list

    //After this operation, the size of the list is zero.

    //Postcondition: length = 0;

    int seqSearch(int item) const;

    //Function to search the list for a given item.

    //Postcondition: If the item is found, returns the location

    // in the array where the item is found;

    // otherwise, returns -1.

    #ifndef H_arrayListType // arrayListType.h

    #define H_arrayListType

    class arrayListType

    {

    public:

    bool isEmpty() const;

    //Function to determine whether the list is empty

    //Postcondition: Returns true if the list is empty;

    // otherwise, returns false.

    bool isFull() const;

    //Function to determine whether the list is full

    //Postcondition: Returns true if the list is full;

    // otherwise, returns false.

    int listSize() const;

    //Function to determine the number of elements in the list

    //Postcondition: Returns the value of length.

    int maxListSize() const;

    //Function to determine the maximum size of the list

    //Postcondition: Returns the value of maxSize.

    void print() const;

    //Function to output the elements of the list

    //Postcondition: Elements of the list are output on the

    // standard output device.

    bool isItemAtEqual(int location, int item) const;

    //Function to determine whether item is the same as

    //the item in the list at the position specified

    //by location

    //Postcondition: Returns true if the list[location]

    // is the same as item; otherwise,

    // returns false.

    void insertAt(int location, int insertItem);

    //Function to insert insertItem in the list at the

    //position specified by location.

    //Postcondition: Starting at location, the elements

    // of the list are shifted down,

    // list[location] = insertItem;, and

    // length++;

    // If the list is full or location is out of

    // range, an appropriate message is displayed.

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    void insert(int insertItem);

    //Function to insert the item specified by the parameter

    //insertItem at the end of the list. However, first the

    //list is searched to see whether the item to be inserted

    //is already in the list.

    //Postcondition: list[length] = insertItem and length++

    // If the item is already in the list or the list

    // is full, an appropriate message is displayed.

    void remove(int removeItem);

    //Function to remove an item from the list. The parameter

    //removeItem specifies the item to be removed.

    //Postcondition: If removeItem is found in the list,

    // it is removed from the list and length is

    // decremented by one.

    arrayListType(int size = 100);

    //constructor

    //Creates an array of the size specified by the

    //parameter size. The default array size is 100.

    //Postcondition: The list points to the array, length = 0,

    // and maxSize = size

    arrayListType (const arrayListType& otherList);

    //copy constructor

    ~arrayListType();

    //destructor

    //Deallocate the memory occupied by the array.

    protected: // later use for the derived class

    int *list; //array to hold the list elements

    int length; //variable to store the length of the list

    int maxSize; //variable to store the maximum size of the list

    };

    #endif

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    void arrayListType::insertAt(int location, int insertItem)

    {

    int i;

    if (location < 0 || location >= maxSize)

    cout << "The position of the item to be inserted "

    << "is out of range." << endl;

    else

    if (length >= maxSize) //list is full

    cout << "Cannot insert in a full list." << endl;

    else

    {

    for (i = length; i > location; i--)

    list[i] = list[i - 1]; //move the elements down

    list[location] = insertItem; //insert insertItem

    //at the specified

    //position

    length++;//increment the length

    }

    } //end insertAt

    void arrayListType::insertEnd(int insertItem)

    {

    if (length >= maxSize) //the list is full

    cout << "Cannot insert in a full list." << endl;

    else

    {

    list[length] = insertItem;//insert the item at the end

    length++;//increment length

    }

    } //end insertEnd

    #include <iostream> // arrayListTypeImp.cpp

    #include <cassert>

    #include "arrayListType.h"

    usingnamespace std;

    bool arrayListType::isEmpty() const

    {

    return (length == 0);

    }

    bool arrayListType::isFull() const

    {

    return (length == maxSize);

    }

    int arrayListType::listSize() const

    {

    return length;

    }

    int arrayListType::maxListSize() const

    {

    return maxSize;

    }

    void arrayListType::print() const

    {

    int i;

    for (i = 0; i < length; i++)

    cout << list[i] << " ";

    cout << endl;

    }

    bool arrayListType::isItemAtEqual(int location, int item) const

    {

    return(list[location] == item);

    }

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    arrayListType::arrayListType(int size)

    {

    if (size <= 0)

    {

    cout << "The array size must be positive. Creating "

    << "an array of size 100. " << endl;

    maxSize = 100;

    }

    else

    maxSize = size;

    length = 0;

    list = newint[maxSize];

    assert(list != NULL);

    }

    arrayListType::~arrayListType()

    {

    delete [ ] list;

    }

    //copy constructor

    arrayListType::arrayListType(const arrayListType& otherList)

    {

    int j;

    maxSize = otherList.maxSize;

    length = otherList.length;

    list = newint[maxSize]; //create the array

    assert(list != NULL); //terminate if unable to allocate memory space

    for (j = 0; j < length; j++) //copy otherList

    list [j] = otherList.list[j];

    }//end copy constructor

    void arrayListType::removeAt(int location)

    {

    int i;

    if (location < 0 || location >= length)

    cout << "The location of the item to be removed "

    << "is out of range." << endl;

    else

    {

    for (i = location; i < length - 1; i++)

    list[i] = list[i+1];

    length--;

    }

    } //end removeAt

    void arrayListType::retrieveAt(int location, int& retItem)

    {

    if (location < 0 || location >= length)

    cout << "The location of the item to be retrieved is "

    << "out of range." << endl;

    else

    retItem = list[location];

    } // retrieveAt

    void arrayListType::replaceAt(int location, int repItem)

    {

    if (location < 0 || location >= length)

    cout << "The location of the item to be replaced is "

    << "out of range." << endl;

    else

    list[location] = repItem;

    } //end replaceAt

    void arrayListType::clearList()

    {

    length = 0;

    } // end clearList

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    void arrayListType::remove(int removeItem)

    {

    int loc;

    if (length == 0)

    cout << "Cannot delete from an empty list." << endl;

    else

    {

    loc = seqSearch(removeItem);

    if (loc != -1)

    removeAt(loc);

    else

    cout << "The tem to be deleted is not in the list."

    << endl;

    }

    } //end remove

    int arrayListType::seqSearch(int item) const

    {

    int loc;

    bool found = false;

    for (loc = 0; loc < length; loc++)

    if (list[loc] == item)

    {

    found = true;

    break;

    }

    if (found)

    return loc;

    else

    return -1;

    } //end seqSearch

    void arrayListType::insert(int insertItem)

    {

    int loc;

    if (length == 0) //list is empty

    list[length++] = insertItem; //insert the item and

    //increment the length

    else

    if (length == maxSize)

    cout << "Cannot insert in a full list." << endl;

    else

    {

    loc = seqSearch(insertItem);

    if (loc == -1) //the item to be inserted

    //does not exist in the list

    list[length++] = insertItem;

    else

    cout << "the item to be inserted is already "

    << "in the list. No duplicates are "

    << "allowed." << endl;

    }

    } //end insert

    • Remove: delete an item from the list

    • The item to be deleted is passed as a parameter to this function

    • First call search to determine if item to be deleted is in the list

    • If found removefrom the list and decrement length by 1

    • Insert: add a new item to the list

    • Duplicates are not allowed

    • Search list to determine if item to be inserted is already in the list

      • If not in the list, insert at the end of the list and increment length by 1

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    //test copy constructor

    testCopyConstructor(list);//Line 18

    cout << "Line 19: The list after the copy "

    << "constructor." << endl;//Line 19

    list.print();//Line 20

    cout << "Line 21: The list size is: "

    << list.listSize() << endl;//Line 21

    return 0;//Line 22

    }

    void testCopyConstructor(arrayListType testList)

    {

    cout << "Line 23: Inside the function "

    << "testCopyConstructor." << endl;//Line 23

    testList.print();//Line 24

    cout << "Line 25: The list size is: "

    << testList.listSize() << endl;//Line 25

    }

    #include <iostream> // testProgArrayBasedList.cpp

    #include "arrayListType.h"

    usingnamespace std;

    void testCopyConstructor(arrayListType testList);

    int main()

    {

    arrayListType list;//Line 1

    int num;//Line 2

    cout << "Line 3: Enter numbers ending with -999"

    << endl;//Line 3

    cin >> num;//Line 4

    while(num != -999)//Line 5

    {

    list.insert(num);//Line 6

    cin >> num;//Line 7

    }

    cout << "Line 8: The list you entered is: "

    << endl;//Line 8

    list.print();//Line 9

    cout << "Line 10: The list size is: "

    << list.listSize() << endl;//Line 10

    cout << "Line 11: Enter the item to be deleted: ";//Line 11

    cin >> num; //Line 12

    cout << endl; //Line 13

    list.remove(num); //Line 14

    cout << "Line 15: After removing " << num

    << " the list is: " << endl; //Line 15

    list.print(); //Line 16

    cout << "Line 16: The list size is: "

    << list.listSize() << endl; //Line 17

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Copy constructor2

    Copy Constructor

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Search

    Search

    • The following function performs a sequential search on a list:

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Inheritance pointers and virtual functions

    Inheritance, Pointers, And Virtual Functions

    • C++ allows the user to pass an object of a derived class to a formal parameter of the base class type

    • Compile-time binding: necessary code to call a specific function is generated by the compiler

      • Also known as static binding

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Inheritance pointers and virtual functions continued

    Inheritance, Pointers, And Virtual Functions (continued)

    • With virtual functions, binding occurs during execution, not at compile time

      • Called run-time binding

      • Compiler does not generate code to call a specific function

        • Generates enough information for the run-time system to generate specific code for the appropriate function call

          • Also known as dynamic binding

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    // baseClass.h

    #ifndef H_baseClassVirtual

    #define H_baseClassVirtual

    class baseClass

    {

    public:

    virtualvoidprint();

    //virtual function

    baseClass( int u = 0);

    private:

    int x;

    };

    #endif

    // baseClassImpl.cpp

    #include <iostream>

    #include "baseClass.h"

    usingnamespace std;

    void baseClass::print()

    {

    cout<<"In baseClass x =

    "<<x<<endl;

    }

    baseClass::baseClass(int u)

    {

    x = u;

    }

    // derivedClass.cpp

    #include <iostream>

    #include "derivedClass.h"

    usingnamespace std;

    void derivedClass::print()

    {

    cout<<"In derivedClass ***: ";

    baseClass::print();

    cout<<"In derivedClass a =

    "<<a<<endl;

    }

    derivedClass::derivedClass(int u, int v)

    : baseClass(u)

    {

    a = v;

    }

    // derivedClass.h

    #ifndef H_derivedClassVirtual

    #define H_derivedClassVirtual

    #include "baseClass.h"

    class derivedClass: public baseClass

    {

    public:

    voidprint();

    derivedClass(int u = 0, int v = 0);

    private:

    int a;

    };

    #endif

    // mainProgram.cpp

    #include <iostream>

    #include "derivedClass.h"

    usingnamespace std;

    void callPrint(baseClass& p);

    int main()

    {

    baseClass one(5);//Line 1

    derivedClass two(3, 15);//Line 2

    one.print();//Line 3

    two.print();//Line 4

    cout<<"*** Calling the function callPrint ***"

    <<endl;//Line 5

    callPrint(one); //Line 6

    callPrint(two); //Line 7 // run-time binding // b/c of print() declaration in the base class is virtual

    return 0;

    }

    declaring a member function to be virtual instructs

    the compiler to generate code that guarantees dynamic binding

    void callPrint( baseClass&p )

    {

    p.print();

    }

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    // mainProgram.cpp

    #include <iostream>

    #include "derivedClass.h"

    usingnamespace std;

    void callPrint(baseClass& p);

    int main()

    {

    baseClass one(5);//Line 1

    derivedClass two(3, 15);//Line 2

    one.print();//Line 3

    two.print();//Line 4

    cout<<"*** Calling the function callPrint ***"

    <<endl;//Line 5

    callPrint(one); //Line 6

    callPrint(two); //Line 7 // run-time binding // b/c of print() declaration in the base class as virtual

    return 0;

    }

    // // mainProgram.cpp - equivalent code of the previous mainProgram.cpp:

    #include <iostream>

    #include "derivedClass.h"

    usingnamespace std;

    void callPrint(baseClass *p);

    int main()

    {

    baseClass *q; //Line 1

    derivedClass *r; //Line 2

    q = new baseClass(5); //Line 3

    r = new derivedClass(3,15);//Line 4

    q->print();//Line 5

    r->print();//LIne 6

    cout << "*** Calling the function callPrint ***"

    << endl;//Line 7

    callPrint(q);//Line 8

    callPrint(r);//Line 9

    // pointer of the derived class is passed as an actual parameter

    return 0;

    }

    voidcallPrint(baseClass *p) // a formal parameter is a pointer to a class

    { // pointer of the derived class is passed as an actual parameter

    p->print(); // p uses a virtual function of the base class so

    // we can effectively pass a derived class object as an actual parameter to p

    }

    // if p passes as a value parameter callPrint(baseClass p);

    // it will copy to p only the data member x and p->print() and will be executed from the base class

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Using virtual functions in c

    Using virtual functions in C++

    • dynamic binding requires pass-by-reference when passing a class object to a function

    • in the declaration for a virtual function, the word virtual appears only in the base class

    • if a base class declares a virtual function, it must implement that function, even if the body is empty

    • a derived class is not required to re-implement a virtual function.

      • If it does not, the base class version is used

    expanded by J. Goetz, 2004


    Classes and virtual destructors

    Classes and Virtual Destructors

    • Destructor is automatically executed when the class object goes out of scope

    • Virtual destructor of a base class automatically makes destructor of a derived class virtual

    • If a derivedclass object is passed to a formal parameter of the base class type,

      • when the object goes out of scope, the destructor of the derived class executes and

      • After executing the destructor of the derived class, the destructor of the base class executes

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Reference types

    Reference Types

    int & intRef;

    • declares that intRef is a variable that contain the address of an int variable

    • General syntax:

      DataType & Variable, & Variable ….;

    • Only the operation is defined is initialization:

      • i.e. explicit initialization or

      • passing an argument to a parameter or

      • initialization by returning a function value.

    • Reference and pointer variables contain addresses of data object

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Reference and pointer variables differences

    Reference and pointer variables differences

    • the dereferencing and address of operators (* and & ) are not used with reference variables.

      • After a reference variable has been declared, the compiler invisibly dereferences every single appearance of that reference variable.

    • Only the operation is defined at initialization.

      • the compiler treats a reference variable as if it were a constant pointer

        • it cannot be reassigned after being initialized

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Address of operator classes

    Address of Operator & Classes

    • The address of operator can create aliases to an object

    • Consider the following statements:

      int x;

      int &y = x;

      x and y refer to the same memory location

      y is like a constant pointer variable

    • The statement y = 25; sets the value of y and hence of x to 25

    • Similarly, the statement x = 2 * x + 30;

      • updates the value of x and hence of y

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    C programming program design including data structures second edition

    //header file testAdd.h

    #ifndef H_testAdd

    #define H_testAdd

    class testAddress

    {

    public:

    voidsetX(int);

    voidprintX() const;

    int&addressOfX(); //this function

    // returns the address

    //of the private data member

    private:

    int x;

    };

    #endif

    //Test program.

    #include <iostream>

    #include "testAdd.h“

    usingnamespace std;

    int main()

    {

    testAddress a;

    int &y = a.addressOfX();

    a.setX(50);

    cout << "x in class testAddress = ";

    a.printX(); // prints x = 50

    cout << endl;

    y = 25;

    cout << "After y = 25, x in class testAddress = ";

    a.printX(); / / prints x = 25

    cout << endl;

    return 0;

    }

    // Implementation file testAdd.cpp

    #include <iostream>

    #include "testAdd.h“

    usingnamespace std;

    void testAddress::setX(int inX)

    {

    x = inX;

    }

    void testAddress::printX() const

    {

    cout << x;

    }

    int& testAddress::addressOfX()

    {

    return x;

    }

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Summary

    Summary

    • Pointer variables contain the addresses of other variables as their values

    • Declare a pointer variable with an asterisk, *, between the data type and the variable

    • & is called the address of operator

      • & returns the address of its operand

    • Unary operator * is the dereference operator

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Summary1

    Summary

    • The member access operator arrow, ->, accesses thecomponent of an objectpointed to by a pointer

    • Dynamic variable: created during execution

    • Operator new creates a dynamic variable

    • Operator delete deallocates memory occupied by a dynamic variable

    • Dynamic array: created during execution

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


    Summary2

    Summary

    • Shallow copy: two or more pointers of the same type point to the same memory

    • Deep copy: two or more pointers of the same type have their own copies of the data

    • List: homogeneous collection of elements

    • C++ allows the user to pass an object of a derived class to a formal parameter of the baseclass type

    • The binding of virtual functions occurs at execution time, not at compile time, and is called dynamic or run-time binding

    C++ Programming: Program Design Including Data Structures, Second Edition expanded by J. Goetz, 2004


  • Login