polymorphism i

63
Comput er Prog ramming Fall 2012 Polymorphism (R un -tim e Pol ym or phis m ) (Vir t u al Fun ct ions) Mu ham m ad K ashif K han

Upload: shakeel-ahmed

Post on 13-Apr-2018

226 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 1/63

Computer Programming

Fall 2012

Polymorphism

(Run-time Polymorphism)

(Virtual Functions)

Muhammad Kashif Khan

Page 2: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 2/63

Objectives• Pointer Data Type and Pointer Variables

 – Declaring Pointer Variables• Address of Operator (&)

• Dereferencing Operator (*)

• Classes, Structs, and Pointer Variables

• Initializing Pointer Variables (null pointer)

• Dynamic Variables – Operator new

 – Operator del et e

• Operations on Pointer Variables

• Dynamic Arrays

• Shallow versus Deep Copy and Pointers

• Classes and Pointers: Some Peculiarities

 – Destructor 

 – Assignment Operator 

 – Copy Constructor 2

Page 3: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 3/63

Objectives (cont'd.)

• Inheritance, Pointers, and Virtual Functions

 – Classes and Virtual Destructors

• Abstract Classes and Pure Virtual Functions

• Address of Operator and Classes

3

Page 4: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 4/63

Polymorphism

4

Page 5: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 5/63

Pointer Data Type and Pointer

Variables• Pointer variable: content is a memory

address

• There is no name associated with thepointer data type in C++

5

Page 6: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 6/63

Declaring Pointer Variables

• Syntax:

• Examples:i nt *p;char *ch;

• These statements are equivalent:

i nt *p;i nt * p;i nt * p;

6

Page 7: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 7/63

Declaring Pointer Variables

(cont'd.)• In the statement:

i nt * p, q;

only p is the pointer variable, not q; here qis an i nt  variable

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

i nt   *p, q;

i nt *p, *q;

7

Page 8: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 8/63

Working with Pointer Variables

• Because the value of a pointer is amemory address, a pointer can store the

address of a memory space of the

designated type.

• For example, if p is a pointer of type i nt ,

p can store the address of any memoryspace of type i nt .

• C++ provides two operators: –  addr ess of oper at or ( &)  and

 –  der ef er enci ng oper at or ( *)

to work with pointers.   8

Page 9: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 9/63

 Address of Operator (&)• The ampersand,   &, is called the address of 

operator 

• The address of operator is a unary operator that

returns the address of its operand

• For example, given the statements:i nt x;

i nt *p;

• the statement:

p = &x;

assigns the address of x to p.

• That is, x and the value of p refer to the same

memory location.  9

Page 10: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 10/63

Dereferencing Operator (*)

• When used as a unary operator,   *   is the

dereferencing operator or indirection operator 

 – Refers to object to which its operand (i.e., the

pointer) points

• Example:

 – To print the value of  x, using p:

 – To store a value in x, using p:

10

Page 11: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 11/63

11

Dereferencing Operator (*)

(cont’d.)

Page 12: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 12/63

Classes, Structs, and Pointer

Variables• You can declare pointers to other data

types:

 –  st udent  is an object of type st udent Type;st udent Pt r   is a pointer variable of typest udent Type

12

Page 13: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 13/63

Classes, Structs, and Pointer

Variables (cont'd.)• To store address of    st udent   in

st udent Pt r :

st udent Pt r = &st udent ;• To store   3. 9   in component   gpa   of 

st udent :( *st udent Pt r ) . gpa = 3. 9;

 – () used because dot operator has higher precedence than dereferencing operator 

 – Alternative: use   member access operator arrow (- >)

13

Page 14: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 14/63

Classes, Structs, and Pointer

Variables (cont'd.)• The syntax for accessing a   cl ass

(struct ) member using the operator ->

is:

• Thus,

( *st udent Pt r ) . gpa = 3. 9;

is equivalent to:

st udent Pt r - >gpa = 3. 9;

14

Page 15: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 15/63

Initializing Pointer Variables

(null pointer)• C++ does not automatically initialize variables

• Pointer variables must be initialized if you donot want them to point to anything

 – Initialized using the constant value 0• Called the null pointer 

• Example: p = 0;

 – Or, use the NULL named constant:

• p = NULL; – The number  0   is the only number that can be

directly assigned to a pointer variable

15

Page 16: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 16/63

Dynamic Variables

• Dynamic variables: created during

execution

• C++ creates dynamic variables usingpointers

• Two operators, newand del et e, to create

and destroy dynamic variables

 –  newand del et e are reserved words

16

Page 17: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 17/63

Operator new

• newhas two forms:

 – where i nt Exp  is any expression evaluatingto a positive integer 

• new allocates memory (a variable) of thedesignated type and returns a pointer to it

 – The address of the allocated memory

• The allocated memory is uninitialized

17

Page 18: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 18/63

Operator new(cont'd.)

• The statement: p = &x;

 – stores address of  x in p

• However, no new memory is allocated

• The statement: p = new i nt ;

 – creates a variable during program

execution somewhere in memory, andstores the address of the allocated memoryin p

• To access allocated memory: *p

18

Page 19: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 19/63

19

Operator new(cont'd.)

Page 20: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 20/63

Operator new(cont'd.)

• newallocates memory space of a specific

type and returns the (starting) address of 

the allocated memory space

• If  new  is unable to allocate the required

memory space (for example, there is not

enough memory space), then it throws

bad_al l oc exception – If this exception is not handled, it terminates

the program with an error message

20

Page 21: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 21/63

Operator del et e

21

Page 22: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 22/63

Operator del et e (cont'd.)

• To avoid memory leak, when a dynamic

variable is no longer needed, destroy it

 – Deallocate its memory•   del et e is used to destroy dynamic variables

• Syntax:

 – Tip: to avoid   dangling pointers, set variable toNULL afterwards

22

Page 23: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 23/63

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:

 – Integer values can be added and subtracted from

a pointer variable – Value of one pointer variable can be subtracted

from another pointer variable

23

Page 24: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 24/63

Operations on Pointer Variables

(cont'd.)• Examples:

i nt *p, *q;

p = q;

 – In this case, p == q will evaluate to t r ue,

and p ! = q will evaluate to f al se

i nt *p

doubl e *q;

 – In this case, q++;  increments value of  q by 8,

and p = p + 2;  increments value of  p by 8

24

Page 25: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 25/63

Operations on Pointer Variables

(cont'd.)• Pointer arithmetic can be very dangerous

 – The program can accidentally access the

memory locations of other variables and

change their content without warning

• Some systems might terminate the program with

an appropriate error message

• Always exercise extra care when doing

pointer arithmetic

25

Page 26: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 26/63

Dynamic Arrays

• Dynamic array: array created during the

execution of a program

• Example:i nt *p;

p = new i nt [ 10] ;

*p = 25;

p++; / / t o poi nt t o next ar r ay component

*p = 35;

26

stores 25 into the first memory location

stores 35 into the second memory location

Page 27: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 27/63

Dynamic Arrays (cont'd.)

• C++ allows us to use array notation to

access these memory locations

• The statements:p[ 0] = 25;

p[ 1] = 35;

store  25   and  35   into the first and second array

components, respectively

27

Page 28: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 28/63

Dynamic Arrays (cont'd.)

28

Page 29: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 29/63

Dynamic Arrays (cont'd.)

29

Page 30: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 30/63

Dynamic Arrays (cont'd.)

• The value of  l i st   (1000) is constant

 –  Cannot be altered during program execution

 – The increment and decrement operations

cannot be applied to l i st• If  p is a pointer variable of type i nt , then:

p = l i st ;copies the value of  l i st , the base address of the

array, into p

 – We can perform ++ and -- operations on p

• An array name is a constant pointer 

30

Page 31: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 31/63

31

Dynamic Arrays (cont'd.)

Page 32: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 32/63

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, use &:voi d poi nt er Par amet ers( i nt * &p, doubl e *q)

{

. . .

}

32

Page 33: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 33/63

Pointers and Function Return

Values• A function can return a value of type

pointer:

i nt * t est Exp( . . . ){

. . .

}

33

Page 34: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 34/63

Dynamic Two-Dimensional

 Arrays• You can create dynamic multidimensional

arrays

• Examples:

34

declares boar d to be an array of four

pointers wherein each pointer is of type i nt

creates the rows of boar d

declares boar d to be a pointer to a pointer 

Page 35: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 35/63

Shallow versus Deep Copy and

Pointers

• Assume some data is stored in the array:

• If we execute:

35

Page 36: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 36/63

Shallow versus Deep Copy and

Pointers (cont'd.)• Shallow copy: two or more pointers of the

same type point to the same memory

 – They point to the same data

36

Page 37: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 37/63

Shallow versus Deep Copy and

Pointers (cont'd.)• Deep copy: two or more pointers have

their own data

37

Page 38: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 38/63

Classes and Pointers: Some

Peculiarities

38

Page 39: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 39/63

Destructor 

• If   obj ect One   goes out of scope, themember variables of   obj ect One   are

destroyed – The memory space of the dynamic arraywould stay marked as allocated, even thoughit cannot be accessed

39

Page 40: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 40/63

Destructor (cont'd.)

• Solution:

 – Put the necessary code in the destructor toensure that when   obj ect One   goes out of 

scope, the memory of the array is deallocated

40

Page 41: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 41/63

 Assignment Operator 

41

Page 42: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 42/63

 Assignment Operator (cont'd.)

• If   obj ect Two. p   deallocates memory

space to which it points,  obj ect One. p

becomes invalid

• Solution: extend definition of the

assignment operator to avoid shallow

copying of data

42

Page 43: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 43/63

Copy Constructor 

• This initialization is called the default

member-wise initialization – Initialization due to the constructor, called the

copy constructor  (provided by the compiler)

43

Page 44: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 44/63

Copy Constructor (cont'd.)

• Default initialization leads to shallowcopying of data

• Similar problem occurs when passingobjects by value:

44

Page 45: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 45/63

Copy Constructor (cont'd.)

• Copy constructor automatically executes

in three situations:

 – When an object is declared and initialized by

using the value of another object

 – When, as a parameter, an object is passed by

value

 – When the return value of a function is anobject

45

Page 46: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 46/63

Copy Constructor (cont'd.)

• Solution: properly define copy constructor 

46

Page 47: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 47/63

Copy Constructor (cont'd.)

• For classes with pointer member 

variables, three things are normally done:

 – Include the destructor in the class

 – Overload the assignment operator for the

class

 – Include the copy constructor 

47

Page 48: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 48/63

Inheritance, Pointers, and Virtual

Functions• You can pass an object of a derived class

to a formal parameter of the base class

type

48

Page 49: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 49/63

49

Inheritance, Pointers, and Virtual

Functions (cont'd.)

Page 50: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 50/63

50

Inheritance, Pointers, and Virtual

Functions (cont'd.)

Page 51: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 51/63

Inheritance, Pointers, and Virtual

Functions (cont'd.)• For both statements (Lines 7 and 9), member 

function pr i nt  of  pet Type was executed

 – Because the binding of   pr i nt , in the body

of  cal l Pr i nt , occurred at compile time• Compile-time binding: the necessary code to call

a specific function is generated by the compiler 

 – Also known as static binding or early binding

51

Page 52: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 52/63

Inheritance, Pointers, and Virtual

Functions (cont'd.)• How can we avoid this problem? – Virtual functions (reserved word vi r t ual )

• Virtual function: binding occurs at program

execution time, not at compile time – This kind of binding is called run-time binding

• Run-time binding: compiler does not generatecode to call a specific function; it generates

information to enable run-time system togenerate specific code for the function call – Also known as dynamic or late binding

52

Page 53: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 53/63

Inheritance, Pointers, and Virtual

Functions (cont'd.)

53

Page 54: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 54/63

Classes and Virtual Destructors

• Classes with pointer member variablesshould have the destructor  – Destructor can be designed to deallocate storage

for dynamic objects• If a derived class object is passed to a formal

parameter of the base class type, destructor of the base class executes

 – Regardless of whether object is passed byreference or by value

• Solution: use a virtual destructor (base class)

54

Page 55: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 55/63

Classes and Virtual Destructors

(cont'd.)• The virtual destructor of a base class

automatically makes the destructor of a

derived class virtual

 – After executing the destructor of the derived

class, the destructor of the base class

executes

• If a base class contains virtual functions,make the destructor of the base class

virtual

55

Page 56: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 56/63

 Abstract Classes and Pure Virtual

Functions• Through inheritance we can derive new

classes without designing them from scratch

 – Derived classes inherit existing members of base

class, can add their own members, and alsoredefine or override public and protected member 

functions

 – Base class can contain functions that you would

want each derived class to implement• Base class may contain functions that may not have

meaningful definitions in the base class

56

Page 57: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 57/63

 Abstract Classes and Pure Virtual

Functions (cont'd.)

• To make them pure virtual functions:

57

Page 58: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 58/63

 Abstract Classes and Pure Virtual

Functions (cont'd.)• Abstract class: contains one or more pure

virtual functions

58

You cannot create objects of an abstract class

Page 59: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 59/63

 Abstract Classes and Pure Virtual

Functions (cont'd.)• If we derive r ect angl e from shape and

want to make it a non-abstract class:

 – We must provide the definitions of the pure

virtual functions of its base class

• Note that an abstract class can contain

instance variables, constructors, and

functions that are not pure virtual – The class must provide the definitions of 

constructor/functions that are not pure virtual

59

Page 60: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 60/63

 Address of Operator and

Classes•  &operator can create aliases to an object

• Consider the following statements:

i nt x;i nt &y = x;

x and y refer to the same memory location

y is like a constant pointer variable

•  y = 25;   sets the value of  y (and of  x) to 25

•  x = 2 * x + 30;   updates the value of  xand hence of  y

60

Page 61: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 61/63

 Address of Operator and Classes

(cont'd.)• The address of operator can also be used

to return the address of a private member 

variable of a class

 – However, if you are not careful, this operation

can result in serious errors in the program

61

Page 62: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 62/63

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 dereferencing

operator • Member access operator,   - >, accessesthe object component pointed to by apointer 

62

Page 63: Polymorphism I

7/27/2019 Polymorphism I

http://slidepdf.com/reader/full/polymorphism-i 63/63

Summary (cont'd.)

• Dynamic variable: created during execution – Created using new, deallocated using del et e

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

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

• Can pass an object of a derived class to aformal parameter of the base class type

• Binding of virtual functions occurs at executiontime (dynamic or run-time binding)

63