SlideShare une entreprise Scribd logo
1  sur  42
Chapter 12:
Pointers, Classes, Virtual
Functions, and Abstract Classes
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 the operator and the
dereferencing operator
– Learn how pointers work with classes and
structs
– Discover dynamic variables
2C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Objectives (cont’d.)
– Explore how to use the new and delete
operators to manipulate dynamic variables
– Learn about pointer arithmetic
– Learn how to work with dynamic arrays
– Become familiar with the limitations of range-
based for loops with dynamic arrays
– Explore how pointers work with functions as
parameters and functions as return values
3C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Objectives (cont’d.)
– Become familiar with the shallow and deep copies
of data
– Discover the peculiarities of classes with pointer
member variables
– Learn about virtual functions
– Examine the relationship between the address of
operator and classes
– Become aware of abstract classes
4C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Pointer Data Type and Pointer
Variables
• Pointer variable: content is a memory address
• No name associated with the pointer data
type in C++
5C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Declaring Pointer Variables
• Syntax:
• Examples:
int *p;
char *ch;
• These statements are equivalent:
int *p;
int* p;
int * p;
6C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Declaring Pointer Variables (cont’d.)
• In the statement:
int* p, q;
– Only p is a pointer variable
– q is an int variable
• To avoid confusion, attach the character * to
the variable name:
int *p, q;
int *p, *q;
7C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Address of Operator (&)
• Address of operator (&):
– A unary operator that returns the address of its
operand
• Example:
int x;
int *p;
p = &x;
– Assigns the address of x to p
8C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Dereferencing Operator (*)
• Dereferencing operator (or indirection
operator):
– When used as a unary operator, * refers to object
to which its operand points
• Example:
cout << *p << endl;
– Prints the value stored in the memory location
pointed to by p
9C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Classes, structs, and Pointer
Variables
• You can declare pointers to other data types:
– student is an object of type studentType
– studentPtr is a pointer variable of type
studentType
10C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Classes, structs, and Pointer
Variables (cont’d.)
• To store address of student in
studentPtr:
studentPtr = &student;
• To store 3.9 in component gpa of
student:
(*studentPtr).gpa = 3.9;
– ( ) used because dot operator has higher
precedence than dereferencing operator
– Alternative: use member access operator arrow
(->)
11C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Classes, structs, and Pointer
Variables (cont’d.)
• Syntax to access a class (struct) member
using the operator -> :
• Thus,
(*studentPtr).gpa = 3.9;
is equivalent to:
studentPtr->gpa = 3.9;
12C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Initializing Pointer Variables
• C++ does not automatically initialize variables
• Pointer variables must be initialized if you do
not want them to point to anything
– Initialized using the null pointer: the value 0
– Or, use the NULL named constant
– The number 0 is the only number that can be
directly assigned to a pointer variable
• C++11 includes a nullptr
13C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Dynamic Variables
• Dynamic variables: created during execution
• C++ creates dynamic variables using pointers
• new and delete operators: used to create
and destroy dynamic variables
– new and delete are reserved words in C++
14C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Operator new
• new has two forms:
– intExp is any expression evaluating to a positive
integer
• new allocates memory (a variable) of the
designated type and returns a pointer to it
– The allocated memory is uninitialized
15C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Operator new (cont’d.)
• Example: p = new int;
– Creates a variable during program execution
somewhere in memory
– Stores the address of the allocated memory in p
• To access allocated memory, use *p
• A dynamic variable cannot be accessed
directly
• Because it is unnamed
16C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Operator delete
• Memory leak: previously allocated memory that
cannot be reallocated
– To avoid a memory leak, when a dynamic variable is no
longer needed, destroy it to deallocate its memory
• delete operator: used to destroy dynamic
variables
• Syntax:
17C++ Programming: From Problem Analysis to Program Design, Seventh Edition
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
18C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Operations on Pointer Variables
(cont’d.)
• Pointer arithmetic can be very dangerous:
– Program can accidentally access 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
19C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Dynamic Arrays
• Dynamic array: array created during program
execution
• Example:
int *p;
p = new int[10];
*p = 25;
p++; //to point to next array component
*p = 35;
20
stores 25 into the first memory location
stores 35 into the second memory location
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Dynamic Arrays (cont’d.)
• Can use array notation to access these
memory locations
• Example:
p[0] = 25;
p[1] = 35;
– Stores 25 and 35 into the first and second array
components, respectively
• An array name is a constant pointer
21C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Functions and Pointers
• Pointer variable can be passed as a parameter
either by value or by reference
• As a reference parameter in a function
heading, use &:
void pointerParameters(int* &p, double *q)
{
. . .
}
22C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Pointers and Function Return Values
• A function can return a value of type pointer:
int* testExp(...)
{
. . .
}
23C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Dynamic Two-Dimensional Arrays
• You can create dynamic multidimensional
arrays
• Examples:
24
declares board to be an array of four
pointers wherein each pointer is of type int
declares board to be a pointer to a pointer
creates the rows of board
C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Shallow Versus Deep Copy and
Pointers
• Shallow copy: when two or more pointers of
the same types point to the same memory
– They point to the same data
– Danger: deleting one deletes the data pointed to
by all of them
• Deep copy: when the contents of the memory
pointed to by a pointer are copied to the
memory location of another pointer
– Two copies of the data
25C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Classes and Pointers: Some
Peculiarities
• Example class:
• Example program statements:
26C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Destructor
• If objectOne goes out of scope, its member
variables are destroyed
– Memory space of dynamic array stays marked as
allocated, even though it cannot be accessed
• Solution: in destructor, ensure that when
objectOne goes out of scope, its array
memory is deallocated:
27C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Assignment Operator
• After a shallow copy: if objectTwo.p
deallocates memory space to which it points,
objectOne.p becomes invalid
• Solution: extend definition of the assignment
operator to avoid shallow copying of data
28C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Copy Constructor
• Default member-wise initialization:
• Initializing a class object by using the value of an
existing object of the same type
• Example:
ptrMemberVarType objectThree(objectOne);
• Copy constructor: provided by the compiler
– Performs this initialization
– Leads to a shallow copying of the data if class has
pointer member variables
29C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Copy Constructor (cont’d.)
• Similar problem occurs when passing objects
by value
• Copy constructor automatically executes in
three situations:
– When an object is declared and initialized by using
the value of another object
– When an object is passed by value as a parameter
– When the return value of a function is an object
30C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Copy Constructor (cont’d.)
• Solution: override the copy constructor
• 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
31C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Inheritance, Pointers, and Virtual
Functions
• Can pass an object of a derived class to a
formal parameter of the base class type
• Compile-time binding: the necessary code to
call specific function is generated by compiler
– Also known as static binding or early binding
• Virtual function: binding occurs at program
execution time, not at compile time
– Declared with reserved word virtual
32C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Inheritance, Pointers, and Virtual
Functions (cont’d.)
• Run-time binding:
– Compiler does not generate code to call a specific
function: it generates information to enable run-
time system to generate specific code for the
function call
– Also known as dynamic or late binding
• Note: cannot pass an object of base class type
to a formal parameter of the derived class
type
33C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Inheritance, Pointers, and Virtual
Functions (cont’d.)
• Values of a derived class object can be copied
into a base class object
• Slicing problem: if derived class has more data
members than base class, some data could be
lost
• Solution: use pointers for both base and
derived class objects
34C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Classes and Virtual Destructors
• Classes with pointer member variables should
have the destructor
– Destructor should 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 by reference
or by value
• Solution: use a virtual destructor (base class)
35C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Classes and Virtual Destructors
(cont’d.)
• 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
36C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Abstract Classes
and Pure Virtual Functions
• New classes can be derived through inheritance
without designing them from scratch
– Derived classes inherit existing members of base class
– Can add their own members
– Can redefine or override public and protected
member functions
• Base class can contain functions that you would
want each derived class to implement
• However, base class may contain functions that may
not have meaningful definitions in the base class
37C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Abstract Classes and Pure Virtual
Functions (cont’d.)
• Pure virtual functions:
– Do not have definitions (bodies have no code)
• Example: virtual void draw() = 0;
• Abstract class: a class with one or more virtual
functions
– Can contain instance variables, constructors, and
functions that are not pure virtual
– Class must provide the definitions of
constructor/functions that are not pure virtual
38C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Address of Operator and Classes
• & operator can create aliases to an object
• Example:
int x;
int &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 value of x and y
39C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Address of Operator and Classes
(cont’d.)
• 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
40C++ Programming: From Problem Analysis to Program Design, Seventh Edition
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
• Address of operator (&)returns the address of its
operand
• Unary operator * is the dereferencing operator
• Member access operator (->) accesses the object
component pointed to by a pointer
41C++ Programming: From Problem Analysis to Program Design, Seventh Edition
Summary (cont’d.)
• Dynamic variable: created during execution
– Created using new, deallocated using delete
• 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
• Binding of virtual functions occurs at
execution time (dynamic or run-time binding)
42C++ Programming: From Problem Analysis to Program Design, Seventh Edition

Contenu connexe

Tendances

9781285852744 ppt ch11
9781285852744 ppt ch119781285852744 ppt ch11
9781285852744 ppt ch11Terry Yoast
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16Terry Yoast
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18Terry Yoast
 
9781285852744 ppt ch09
9781285852744 ppt ch099781285852744 ppt ch09
9781285852744 ppt ch09Terry Yoast
 
Computer Programming
Computer ProgrammingComputer Programming
Computer ProgrammingBurhan Fakhar
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14Terry Yoast
 
Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...Warren0989
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14IIUM
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14IIUM
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02Terry Yoast
 

Tendances (20)

9781285852744 ppt ch11
9781285852744 ppt ch119781285852744 ppt ch11
9781285852744 ppt ch11
 
9781285852744 ppt ch16
9781285852744 ppt ch169781285852744 ppt ch16
9781285852744 ppt ch16
 
9781285852744 ppt ch18
9781285852744 ppt ch189781285852744 ppt ch18
9781285852744 ppt ch18
 
9781285852744 ppt ch09
9781285852744 ppt ch099781285852744 ppt ch09
9781285852744 ppt ch09
 
Computer Programming
Computer ProgrammingComputer Programming
Computer Programming
 
9781285852744 ppt ch14
9781285852744 ppt ch149781285852744 ppt ch14
9781285852744 ppt ch14
 
Lesson 13 object and class
Lesson 13 object and classLesson 13 object and class
Lesson 13 object and class
 
Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...Solutions manual for c++ programming from problem analysis to program design ...
Solutions manual for c++ programming from problem analysis to program design ...
 
Lesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th stepLesson 4.2 5th and 6th step
Lesson 4.2 5th and 6th step
 
Lesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving processLesson 2 beginning the problem solving process
Lesson 2 beginning the problem solving process
 
Lesson 5 .1 selection structure
Lesson 5 .1 selection structureLesson 5 .1 selection structure
Lesson 5 .1 selection structure
 
Lesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving processLesson 4.1 completing the problem solving process
Lesson 4.1 completing the problem solving process
 
Lesson 5.2 logical operators
Lesson 5.2 logical operatorsLesson 5.2 logical operators
Lesson 5.2 logical operators
 
Lesson 3.2 data types for memory location
Lesson 3.2 data types for memory locationLesson 3.2 data types for memory location
Lesson 3.2 data types for memory location
 
Chapter 4 5
Chapter 4 5Chapter 4 5
Chapter 4 5
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14
 
Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14Csc1100 lecture03 ch03-pt2-s14
Csc1100 lecture03 ch03-pt2-s14
 
9781111530532 ppt ch02
9781111530532 ppt ch029781111530532 ppt ch02
9781111530532 ppt ch02
 
Lesson 3.1 variables and constant
Lesson 3.1 variables and constantLesson 3.1 variables and constant
Lesson 3.1 variables and constant
 
Chap02
Chap02Chap02
Chap02
 

En vedette

Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Zidny Nafan
 
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj SahniFundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj SahniMunawar Ahmed
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP ImplementationFridz Felisco
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++Nitin Jawla
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaManoj_vasava
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsTech
 
Data Structure
Data StructureData Structure
Data Structuresheraz1
 
Templates presentation
Templates presentationTemplates presentation
Templates presentationmalaybpramanik
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class StructureHadziq Fabroyir
 
stacks in algorithems and data structure
stacks in algorithems and data structurestacks in algorithems and data structure
stacks in algorithems and data structurefaran nawaz
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patilwidespreadpromotion
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 

En vedette (20)

C++ Interview Questions
C++ Interview QuestionsC++ Interview Questions
C++ Interview Questions
 
Forest resources
Forest resourcesForest resources
Forest resources
 
Lec5
Lec5Lec5
Lec5
 
Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0Kuliah1 Struktur Data V1.0
Kuliah1 Struktur Data V1.0
 
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj SahniFundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
Fundamentals of Data Structures in C++ - Ellis Horowitz, Sartaj Sahni
 
OOP C++
OOP C++OOP C++
OOP C++
 
C++ OOP Implementation
C++ OOP ImplementationC++ OOP Implementation
C++ OOP Implementation
 
Control structures in c++
Control structures in c++Control structures in c++
Control structures in c++
 
Exception handling in c++ by manoj vasava
Exception handling in c++ by manoj vasavaException handling in c++ by manoj vasava
Exception handling in c++ by manoj vasava
 
The Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming ConceptsThe Three Basic Selection Structures in C++ Programming Concepts
The Three Basic Selection Structures in C++ Programming Concepts
 
Data Structure
Data StructureData Structure
Data Structure
 
Templates presentation
Templates presentationTemplates presentation
Templates presentation
 
#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure#OOP_D_ITS - 4th - C++ Oop And Class Structure
#OOP_D_ITS - 4th - C++ Oop And Class Structure
 
stacks in algorithems and data structure
stacks in algorithems and data structurestacks in algorithems and data structure
stacks in algorithems and data structure
 
Data structures
Data structuresData structures
Data structures
 
AI: Logic in AI
AI: Logic in AIAI: Logic in AI
AI: Logic in AI
 
4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil4. Recursion - Data Structures using C++ by Varsha Patil
4. Recursion - Data Structures using C++ by Varsha Patil
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Exception handling
Exception handlingException handling
Exception handling
 
polymorphism
polymorphism polymorphism
polymorphism
 

Similaire à 9781285852744 ppt ch12

PPT slide_chapter 02 Basic element of C++.ppt
PPT slide_chapter 02 Basic element of C++.pptPPT slide_chapter 02 Basic element of C++.ppt
PPT slide_chapter 02 Basic element of C++.pptmasadjie
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10Terry Yoast
 
9781423902096_PPT_ch07.ppt
9781423902096_PPT_ch07.ppt9781423902096_PPT_ch07.ppt
9781423902096_PPT_ch07.pptLokeshK66
 
Review chapter 1 2-3
Review chapter 1 2-3Review chapter 1 2-3
Review chapter 1 2-3ahmed22dg
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaAdan Hubahib
 
9781423902096_PPT_ch08.ppt
9781423902096_PPT_ch08.ppt9781423902096_PPT_ch08.ppt
9781423902096_PPT_ch08.pptLokeshK66
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptManivannan837728
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringSri Harsha Pamu
 
UoN-Lec_12_Control_Structure.pdf
UoN-Lec_12_Control_Structure.pdfUoN-Lec_12_Control_Structure.pdf
UoN-Lec_12_Control_Structure.pdfmadihamaqbool6
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdfssusere19c741
 
CIS110 Computer Programming Design Chapter (2)
CIS110 Computer Programming Design Chapter  (2)CIS110 Computer Programming Design Chapter  (2)
CIS110 Computer Programming Design Chapter (2)Dr. Ahmed Al Zaidy
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxVigneshkumar Ponnusamy
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#ANURAG SINGH
 
Chapter12 python object oriented concepts.ppt
Chapter12 python object oriented concepts.pptChapter12 python object oriented concepts.ppt
Chapter12 python object oriented concepts.pptnaveenkumarkiot12
 
Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Mohamed El Desouki
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxvrickens
 

Similaire à 9781285852744 ppt ch12 (20)

PPT slide_chapter 02 Basic element of C++.ppt
PPT slide_chapter 02 Basic element of C++.pptPPT slide_chapter 02 Basic element of C++.ppt
PPT slide_chapter 02 Basic element of C++.ppt
 
C++.ppt
C++.pptC++.ppt
C++.ppt
 
9781285852744 ppt ch10
9781285852744 ppt ch109781285852744 ppt ch10
9781285852744 ppt ch10
 
9781423902096_PPT_ch07.ppt
9781423902096_PPT_ch07.ppt9781423902096_PPT_ch07.ppt
9781423902096_PPT_ch07.ppt
 
Review chapter 1 2-3
Review chapter 1 2-3Review chapter 1 2-3
Review chapter 1 2-3
 
Chapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of JavaChapter 2 - Basic Elements of Java
Chapter 2 - Basic Elements of Java
 
9781423902096_PPT_ch08.ppt
9781423902096_PPT_ch08.ppt9781423902096_PPT_ch08.ppt
9781423902096_PPT_ch08.ppt
 
lecture_3.ppt
lecture_3.pptlecture_3.ppt
lecture_3.ppt
 
U19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).pptU19CS101 - PPS Unit 4 PPT (1).ppt
U19CS101 - PPS Unit 4 PPT (1).ppt
 
C++ ch2
C++ ch2C++ ch2
C++ ch2
 
Lec16-CS110 Computational Engineering
Lec16-CS110 Computational EngineeringLec16-CS110 Computational Engineering
Lec16-CS110 Computational Engineering
 
UoN-Lec_12_Control_Structure.pdf
UoN-Lec_12_Control_Structure.pdfUoN-Lec_12_Control_Structure.pdf
UoN-Lec_12_Control_Structure.pdf
 
0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf0-Slot11-12-Pointers.pdf
0-Slot11-12-Pointers.pdf
 
CIS110 Computer Programming Design Chapter (2)
CIS110 Computer Programming Design Chapter  (2)CIS110 Computer Programming Design Chapter  (2)
CIS110 Computer Programming Design Chapter (2)
 
Fundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptxFundamentals of Data Structures Unit 1.pptx
Fundamentals of Data Structures Unit 1.pptx
 
Introduction to C#
Introduction to C#Introduction to C#
Introduction to C#
 
Chapter12 python object oriented concepts.ppt
Chapter12 python object oriented concepts.pptChapter12 python object oriented concepts.ppt
Chapter12 python object oriented concepts.ppt
 
Chapter12.ppt
Chapter12.pptChapter12.ppt
Chapter12.ppt
 
Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++Basic Programming concepts - Programming with C++
Basic Programming concepts - Programming with C++
 
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docxJLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
JLK Chapter 5 – Methods and ModularityDRAFT January 2015 Edition.docx
 

Plus de Terry Yoast

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12Terry Yoast
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11Terry Yoast
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09Terry Yoast
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08Terry Yoast
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07Terry Yoast
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06Terry Yoast
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05Terry Yoast
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04Terry Yoast
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 

Plus de Terry Yoast (20)

9781305078444 ppt ch12
9781305078444 ppt ch129781305078444 ppt ch12
9781305078444 ppt ch12
 
9781305078444 ppt ch11
9781305078444 ppt ch119781305078444 ppt ch11
9781305078444 ppt ch11
 
9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch09
9781305078444 ppt ch099781305078444 ppt ch09
9781305078444 ppt ch09
 
9781305078444 ppt ch08
9781305078444 ppt ch089781305078444 ppt ch08
9781305078444 ppt ch08
 
9781305078444 ppt ch07
9781305078444 ppt ch079781305078444 ppt ch07
9781305078444 ppt ch07
 
9781305078444 ppt ch06
9781305078444 ppt ch069781305078444 ppt ch06
9781305078444 ppt ch06
 
9781305078444 ppt ch05
9781305078444 ppt ch059781305078444 ppt ch05
9781305078444 ppt ch05
 
9781305078444 ppt ch04
9781305078444 ppt ch049781305078444 ppt ch04
9781305078444 ppt ch04
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch02
9781305078444 ppt ch029781305078444 ppt ch02
9781305078444 ppt ch02
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 

Dernier

Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxNikitaBankoti2
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docxPoojaSen20
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibitjbellavia9
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxDenish Jangid
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17Celine George
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphThiyagu K
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.christianmathematics
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701bronxfugly43
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin ClassesCeline George
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 

Dernier (20)

Role Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptxRole Of Transgenic Animal In Target Validation-1.pptx
Role Of Transgenic Animal In Target Validation-1.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Z Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot GraphZ Score,T Score, Percential Rank and Box Plot Graph
Z Score,T Score, Percential Rank and Box Plot Graph
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 

9781285852744 ppt ch12

  • 1. Chapter 12: Pointers, Classes, Virtual Functions, and Abstract Classes
  • 2. 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 the operator and the dereferencing operator – Learn how pointers work with classes and structs – Discover dynamic variables 2C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 3. Objectives (cont’d.) – Explore how to use the new and delete operators to manipulate dynamic variables – Learn about pointer arithmetic – Learn how to work with dynamic arrays – Become familiar with the limitations of range- based for loops with dynamic arrays – Explore how pointers work with functions as parameters and functions as return values 3C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 4. Objectives (cont’d.) – Become familiar with the shallow and deep copies of data – Discover the peculiarities of classes with pointer member variables – Learn about virtual functions – Examine the relationship between the address of operator and classes – Become aware of abstract classes 4C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 5. Pointer Data Type and Pointer Variables • Pointer variable: content is a memory address • No name associated with the pointer data type in C++ 5C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 6. Declaring Pointer Variables • Syntax: • Examples: int *p; char *ch; • These statements are equivalent: int *p; int* p; int * p; 6C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 7. Declaring Pointer Variables (cont’d.) • In the statement: int* p, q; – Only p is a pointer variable – q is an int variable • To avoid confusion, attach the character * to the variable name: int *p, q; int *p, *q; 7C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 8. Address of Operator (&) • Address of operator (&): – A unary operator that returns the address of its operand • Example: int x; int *p; p = &x; – Assigns the address of x to p 8C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 9. Dereferencing Operator (*) • Dereferencing operator (or indirection operator): – When used as a unary operator, * refers to object to which its operand points • Example: cout << *p << endl; – Prints the value stored in the memory location pointed to by p 9C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 10. Classes, structs, and Pointer Variables • You can declare pointers to other data types: – student is an object of type studentType – studentPtr is a pointer variable of type studentType 10C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 11. Classes, structs, and Pointer Variables (cont’d.) • To store address of student in studentPtr: studentPtr = &student; • To store 3.9 in component gpa of student: (*studentPtr).gpa = 3.9; – ( ) used because dot operator has higher precedence than dereferencing operator – Alternative: use member access operator arrow (->) 11C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 12. Classes, structs, and Pointer Variables (cont’d.) • Syntax to access a class (struct) member using the operator -> : • Thus, (*studentPtr).gpa = 3.9; is equivalent to: studentPtr->gpa = 3.9; 12C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 13. Initializing Pointer Variables • C++ does not automatically initialize variables • Pointer variables must be initialized if you do not want them to point to anything – Initialized using the null pointer: the value 0 – Or, use the NULL named constant – The number 0 is the only number that can be directly assigned to a pointer variable • C++11 includes a nullptr 13C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 14. Dynamic Variables • Dynamic variables: created during execution • C++ creates dynamic variables using pointers • new and delete operators: used to create and destroy dynamic variables – new and delete are reserved words in C++ 14C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 15. Operator new • new has two forms: – intExp is any expression evaluating to a positive integer • new allocates memory (a variable) of the designated type and returns a pointer to it – The allocated memory is uninitialized 15C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 16. Operator new (cont’d.) • Example: p = new int; – Creates a variable during program execution somewhere in memory – Stores the address of the allocated memory in p • To access allocated memory, use *p • A dynamic variable cannot be accessed directly • Because it is unnamed 16C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 17. Operator delete • Memory leak: previously allocated memory that cannot be reallocated – To avoid a memory leak, when a dynamic variable is no longer needed, destroy it to deallocate its memory • delete operator: used to destroy dynamic variables • Syntax: 17C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 18. 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 18C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 19. Operations on Pointer Variables (cont’d.) • Pointer arithmetic can be very dangerous: – Program can accidentally access 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 19C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 20. Dynamic Arrays • Dynamic array: array created during program execution • Example: int *p; p = new int[10]; *p = 25; p++; //to point to next array component *p = 35; 20 stores 25 into the first memory location stores 35 into the second memory location C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 21. Dynamic Arrays (cont’d.) • Can use array notation to access these memory locations • Example: p[0] = 25; p[1] = 35; – Stores 25 and 35 into the first and second array components, respectively • An array name is a constant pointer 21C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 22. Functions and Pointers • Pointer variable can be passed as a parameter either by value or by reference • As a reference parameter in a function heading, use &: void pointerParameters(int* &p, double *q) { . . . } 22C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 23. Pointers and Function Return Values • A function can return a value of type pointer: int* testExp(...) { . . . } 23C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 24. Dynamic Two-Dimensional Arrays • You can create dynamic multidimensional arrays • Examples: 24 declares board to be an array of four pointers wherein each pointer is of type int declares board to be a pointer to a pointer creates the rows of board C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 25. Shallow Versus Deep Copy and Pointers • Shallow copy: when two or more pointers of the same types point to the same memory – They point to the same data – Danger: deleting one deletes the data pointed to by all of them • Deep copy: when the contents of the memory pointed to by a pointer are copied to the memory location of another pointer – Two copies of the data 25C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 26. Classes and Pointers: Some Peculiarities • Example class: • Example program statements: 26C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 27. Destructor • If objectOne goes out of scope, its member variables are destroyed – Memory space of dynamic array stays marked as allocated, even though it cannot be accessed • Solution: in destructor, ensure that when objectOne goes out of scope, its array memory is deallocated: 27C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 28. Assignment Operator • After a shallow copy: if objectTwo.p deallocates memory space to which it points, objectOne.p becomes invalid • Solution: extend definition of the assignment operator to avoid shallow copying of data 28C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 29. Copy Constructor • Default member-wise initialization: • Initializing a class object by using the value of an existing object of the same type • Example: ptrMemberVarType objectThree(objectOne); • Copy constructor: provided by the compiler – Performs this initialization – Leads to a shallow copying of the data if class has pointer member variables 29C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 30. Copy Constructor (cont’d.) • Similar problem occurs when passing objects by value • Copy constructor automatically executes in three situations: – When an object is declared and initialized by using the value of another object – When an object is passed by value as a parameter – When the return value of a function is an object 30C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 31. Copy Constructor (cont’d.) • Solution: override the copy constructor • 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 31C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 32. Inheritance, Pointers, and Virtual Functions • Can pass an object of a derived class to a formal parameter of the base class type • Compile-time binding: the necessary code to call specific function is generated by compiler – Also known as static binding or early binding • Virtual function: binding occurs at program execution time, not at compile time – Declared with reserved word virtual 32C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 33. Inheritance, Pointers, and Virtual Functions (cont’d.) • Run-time binding: – Compiler does not generate code to call a specific function: it generates information to enable run- time system to generate specific code for the function call – Also known as dynamic or late binding • Note: cannot pass an object of base class type to a formal parameter of the derived class type 33C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 34. Inheritance, Pointers, and Virtual Functions (cont’d.) • Values of a derived class object can be copied into a base class object • Slicing problem: if derived class has more data members than base class, some data could be lost • Solution: use pointers for both base and derived class objects 34C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 35. Classes and Virtual Destructors • Classes with pointer member variables should have the destructor – Destructor should 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 by reference or by value • Solution: use a virtual destructor (base class) 35C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 36. Classes and Virtual Destructors (cont’d.) • 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 36C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 37. Abstract Classes and Pure Virtual Functions • New classes can be derived through inheritance without designing them from scratch – Derived classes inherit existing members of base class – Can add their own members – Can redefine or override public and protected member functions • Base class can contain functions that you would want each derived class to implement • However, base class may contain functions that may not have meaningful definitions in the base class 37C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 38. Abstract Classes and Pure Virtual Functions (cont’d.) • Pure virtual functions: – Do not have definitions (bodies have no code) • Example: virtual void draw() = 0; • Abstract class: a class with one or more virtual functions – Can contain instance variables, constructors, and functions that are not pure virtual – Class must provide the definitions of constructor/functions that are not pure virtual 38C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 39. Address of Operator and Classes • & operator can create aliases to an object • Example: int x; int &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 value of x and y 39C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 40. Address of Operator and Classes (cont’d.) • 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 40C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 41. 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 • Address of operator (&)returns the address of its operand • Unary operator * is the dereferencing operator • Member access operator (->) accesses the object component pointed to by a pointer 41C++ Programming: From Problem Analysis to Program Design, Seventh Edition
  • 42. Summary (cont’d.) • Dynamic variable: created during execution – Created using new, deallocated using delete • 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 • Binding of virtual functions occurs at execution time (dynamic or run-time binding) 42C++ Programming: From Problem Analysis to Program Design, Seventh Edition