Starting Out with C++, 3rd Edition
1
POINTERS
Starting Out with C++, 3rd Edition
2
Introduction of Pointer
• Pointers are variables which holds the the
address of other variables.
• Pointer variables are denoted by ‘*ptr’
• Pointers are the derived data type
Starting Out with C++, 3rd Edition
3
Introduction of Pointer
#include <iostream>
using namespace std;
int main()
{ int var1 = 3;
int var2 = 24;
int var3 = 17;
cout << &var1 << endl;
cout << &var2 << endl;
cout << &var3 << endl;
}
Starting Out with C++, 3rd Edition
4
1200 1201 1203
letter number amount
Starting Out with C++, 3rd Edition
5
// This program uses the & operator to determine a variable’s
// address and the sizeof operator to determine its size.
#include <iostream.h>
void main(void)
{
int x = 25;
cout << "The address of x is " << &x << endl;
cout << "The size of x is " << sizeof(x) << " bytesn";
cout << "The value in x is " << x << endl;
}
Starting Out with C++, 3rd Edition
6
Program Output
The address of x is 0x8f05
The size of x is 2 bytes
The value in x is 25
Starting Out with C++, 3rd Edition
7
Pointer Variables
• Pointer variables, which are often just called
pointers, are designed to hold memory
addresses. With pointer variables you can
indirectly manipulate data stored in other
variables.
Starting Out with C++, 3rd Edition
8
Pointers are useful for the following:
• Working with memory locations that
regular variables don’t give you access to
• Working with strings and arrays
• Creating new variables in memory while the
program is running
• Creating arbitrarily-sized lists of values in
memory
Starting Out with C++, 3rd Edition
9
// This program stores the address of a variable in a pointer.
#include <iostream.h>
void main(void)
{
int x = 25;
int *ptr;
ptr = &x; // Store the address of x in ptr
cout << "The value in x is " << x << endl;
cout << "The address of x is " << ptr << endl;
}
Starting Out with C++, 3rd Edition
10
Program Output
The value in x is 25
The address of x is 0x7e00
Starting Out with C++, 3rd Edition
11
0x7e00
25
ptr
x
Address of x: 0x7e00
Starting Out with C++, 3rd Edition
12
Program 9-3
// This program demonstrates the use of the indirection
// operator.
#include <iostream.h>
void main(void)
{
int x = 25;
int *ptr;
ptr = &x; // Store the address of x in ptr
cout << "Here is the value in x, printed twice:n";
cout << x << " " << *ptr << endl;
*ptr = 100;
cout << "Once again, here is the value in x:n";
cout << x << " " << *ptr << endl;
}
Starting Out with C++, 3rd Edition
13
Program Output
Here is the value in x, printed twice:
25 25
Once again, here is the value in x:
100 100
Starting Out with C++, 3rd Edition
14
#include <iostream>
void main(void)
{
int x = 25, y = 50, z = 75;
int *ptr;
cout << "Here are the values of x, y, and z:n";
cout << x << " " << y << " " << z << endl;
ptr = &x; // Store the address of x in ptr
*ptr *= 2; // Multiply value in x by 2
ptr = &y; // Store the address of y in ptr
*ptr *= 2; // Multiply value in y by 2
ptr = &z; // Store the address of z in ptr
*ptr *= 2; // Multiply value in z by 2
cout << "Once again, here are the values of x, y, and z:n";
cout << x << " " << y << " " << z << endl;
}
Starting Out with C++, 3rd Edition
15
Program Output
Here are the values of x, y, and z:
25 50 75
Once again, here are the values of x, y , and z:
50 100 150
Starting Out with C++, 3rd Edition
16
Relationship Between Arrays and
Pointers
• array names can be used as pointers, and
vice-versa.
Starting Out with C++, 3rd Edition
17
// This program shows an array name being dereferenced
// with the * operator.
#include <iostream.h>
void main(void)
{
short numbers[] = {10, 20, 30, 40, 50};
cout << "The first element of the array is ";
cout << *numbers << endl;
}
Starting Out with C++, 3rd Edition
18
Program Output
The first element in the array is 10
Starting Out with C++, 3rd Edition
19
numbers
numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]
Starting Out with C++, 3rd Edition
20
numbers
numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]
(numbers+1) (numbers+2) (numbers+3) (numbers+4)
Starting Out with C++, 3rd Edition
21
// This program processes the contents of an array. Pointer
// notation is used.
#include <iostream.h>
void main(void)
{
int numbers[5];
cout << "Enter five numbers: ";
for (int count = 0; count < 5; count++)
cin >> *(numbers + count);
cout << "Here are the numbers you entered:n";
for (int count = 0; count < 5; count++)
cout << *(numbers + count)<< " ";
cout << endl;
}
Starting Out with C++, 3rd Edition
22
Program Output with Example Input
Enter five numbers: 5 10 15 20 25 [Enter]
Here are the numbers you entered:
5 10 15 20 25
Starting Out with C++, 3rd Edition
23
// This program uses subscript notation with a pointer and
// pointer notation with an array name.
#include <iostream.h>
void main(void)
{
float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};
float *floatPtr; // Pointer to a float
int count; // array index
floatPtr = coins; // floatPtr now points to coins array
cout.precision(2);
cout << "Here are the values in the coins array:n";
Starting Out with C++, 3rd Edition
24
Program continues
for (count = 0; count < 5; count++)
cout << floatPtr[count] << " ";
cout << "nAnd here they are again:n";
for (count = 0; count < 5; count++)
cout << *(coins + count) << " ";
cout << endl;
}
Starting Out with C++, 3rd Edition
25
Program Output
Here are the values in the coins array:
0.05 0.1 0.25 0.5 1
And here they are again:
0.05 0.1 0.25 0.5 1
Starting Out with C++, 3rd Edition
26
// This program uses the address of each element in
the array.
#include <iostream.h>
#include <iomanip.h>
void main(void)
{
float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0};
float *floatPtr; // Pointer to a float
int count; // array index
cout.precision(2);
cout << "Here are the values in the coins array:n";
Starting Out with C++, 3rd Edition
27
Program continues
for (count = 0; count < 5; count++)
{
floatPtr = &coins[count];
cout << *floatPtr << " ";
}
cout << endl;
}
Starting Out with C++, 3rd Edition
28
Program Output
Here are the values in the coins array:
0.05 0.1 0.25 0.5 1
Starting Out with C++, 3rd Edition
29
Pointer Arithmetic
• Some mathematical operations may be
performed on pointers.
– The ++ and – operators may be used to
increment or decrement a pointer variable.
– An integer may be added to or subtracted from
a pointer variable. This may be performed with
the +, - +=, or -= operators.
– A pointer may be subtracted from another
pointer.
Starting Out with C++, 3rd Edition
30
// This program uses a pointer to display the contents
// of an integer array.
#include <iostream.h>
void main(void)
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums, index;
nums = set;
cout << "The numbers in set are:n";
for (index = 0; index < 8; index++)
{
cout << *nums << " ";
nums++;
}
Starting Out with C++, 3rd Edition
31
Program continues
cout << "nThe numbers in set backwards are:n";
for (index = 0; index < 8; index++)
{
nums--;
cout << *nums << " ";
}
}
Starting Out with C++, 3rd Edition
32
Program Output
The numbers in set are:
5 10 15 20 25 30 35 40
The numbers in set backwards are:
40 35 30 25 20 15 10 5
Starting Out with C++, 3rd Edition
33
Initializing Pointers
• Pointers may be initialized with the address
of an existing object.
Starting Out with C++, 3rd Edition
34
Comparing Pointers
• If one address comes before another address
in memory, the first address is considered
“less than” the second. C++’s relational
operators maybe used to compare pointer
values.
Starting Out with C++, 3rd Edition
35
0x5A00
array[0] array[1] array[2] array[3] array[4]
0x5A04 0x5A08 0x5A0C 0x5A0F
(Addresses)
An array of five integers
Starting Out with C++, 3rd Edition
36
Program 9-10
// This program uses a pointer to display the contents
// of an integer array.
#include <iostream.h>
void main(void)
{
int set[8] = {5, 10, 15, 20, 25, 30, 35, 40};
int *nums = set; // Make nums point to set
cout << "The numbers in set are:n";
cout << *nums << " "; // Display first element
while (nums < &set[7])
{
nums++;
cout << *nums << " ";
}
Starting Out with C++, 3rd Edition
37
Program continues
cout << "nThe numbers in set backwards are:n";
cout << *nums << " "; // Display last element
while (nums > set)
{
nums--;
cout << *nums << " ";
}
}
Starting Out with C++, 3rd Edition
38
Program Output
The numbers in set are:
5 10 15 20 25 30 35 40
The numbers in set backwards are:
40 35 30 25 20 15 10 5
Starting Out with C++, 3rd Edition
39
Pointers as Function Parameters
• A pointer can be used as a function
parameter. It gives the function access to
the original argument, much like a reference
parameter does.
Starting Out with C++, 3rd Edition
40
// This program uses two functions that accept addresses of
// variables as arguments.
#include <iostream.h>
// Function prototypes
void getNumber(int *);
void doubleValue(int *);
void main(void)
{
int number;
getNumber(&number) // Pass address of number to getNumber
doubleValue(&number); // and doubleValue.
cout << "That value doubled is " << number << endl;
}
Starting Out with C++, 3rd Edition
41
Program continues
// Definition of getNumber. The parameter, Input, is a pointer.
// This function asks the user for a number. The value entered
// is stored in the variable pointed to by Input.
void getNumber(int *input)
{
cout << "Enter an integer number: ";
cin >> *input;
}
// Definition of doubleValue. The parameter, val, is a pointer.
// This function multiplies the variable pointed to by val by
// two.
void doubleValue(int *val)
{
*val *= 2;
}
Starting Out with C++, 3rd Edition
42
Program Output with Example Input
Enter an integer number: 10 [Enter]
That value doubled is 20
Starting Out with C++, 3rd Edition
43
// This program demonstrates that a pointer may be used as a
// parameter to accept the address of an array. Either subscript
// or pointer notation may be used.
#include <iostream.h>
#include <iomanip.h>
// Function prototypes
void getSales(float *);
float totalSales(float *);
void main(void)
{
float sales[4];
getSales(sales);
cout.precision(2);
Starting Out with C++, 3rd Edition
44
Program continues
cout.setf(ios::fixed | ios::showpoint);
cout << "The total sales for the year are $";
cout << totalSales(sales) << endl;
}
// Definition of getSales. This function uses a pointer to accept
// the address of an array of four floats. The function asks the
// user to enter the sales figures for four quarters, and stores
// those figures in the array. (The function uses subscript
// notation.)
void getSales(float *array)
{
for (int count = 0; count < 4; count++)
{
cout << "Enter the sales figure for quarter ";
cout << (count + 1) << ": ";
cin >> array[count];
}
}
Starting Out with C++, 3rd Edition
45
Program continues
// Definition of totalSales. This function uses a pointer to
// accept the address of an array of four floats. The function
// gets the total of the elements in the array and returns that
// value. (Pointer notation is used in this function.)
float totalSales(float *array)
{
float sum = 0.0;
for (int count = 0; count < 4; count++)
{
sum += *array;
array++;
}
return sum;
}
Starting Out with C++, 3rd Edition
46
Program Output with Example Input
Enter the sales figure for quarter 1: 10263.98 [Enter]
Enter the sales figure for quarter 2: 12369.69 [Enter]
Enter the sales figure for quarter 3: 11542.13 [Enter]
Enter the sales figure for quarter 4: 14792.06 [Enter]
The total sales for the year are $48967.86
Starting Out with C++, 3rd Edition
47
Focus on Software Engineering:
Dynamic Memory Allocation
• Variables may be created and destroyed
while a program is running.
• A pointer than contains the address 0 is
called a null pointer.
• Use the new operator to dynamically
allocate memory.
• Use delete to dynamically deallocate
memory.
Starting Out with C++, 3rd Edition
48
// This program totals and averages the sales figures for any
// number of days. The figures are stored in a dynamically
// allocated array.
#include <iostream.h>
#include <iomanip.h>
void main(void)
{
float *sales, total = 0, average;
int numDays;
cout << "How many days of sales figures do you wish ";
cout << "to process? ";
cin >> numDays;
sales = new float[numDays]; // Allocate memory
Starting Out with C++, 3rd Edition
49
Program continues
if (sales == NULL) // Test for null pointer
{
cout << "Error allocating memory!n";
return;
}
// Get the sales figures from the user
cout << "Enter the sales figures below.n";
for (int count = 0; count < numDays; count++)
{
cout << "Day " << (count + 1) << ": ";
cin >> sales[count];
}
// Calculate the total sales
for (count = 0; count < numDays; count++)
{
total += sales[count];
}
Starting Out with C++, 3rd Edition
50
Program continues
// Calculate the average sales per day
average = total / numDays;
// Display the results
cout.precision(2);
cout.setf(ios::fixed | ios::showpoint);
cout << "nnTotal sales: $" << total << endl;
cout << "average sales: $" << average << endl;
// Free dynamically allocated memory
delete [] sales;
}
Starting Out with C++, 3rd Edition
51
Program Output with Example Input
How many days of sales figures do you wish to process? 5 [Enter]
Enter the sales figures below.
Day 1: 898.63 [Enter]
Day 2: 652.32 [Enter]
Day 3: 741.85 [Enter]
Day 4: 852.96 [Enter]
Day 5: 921.37 [Enter]
total sales: $4067.13
average sales: $813.43
Starting Out with C++, 3rd Edition
52
Focus on Software Engineering:
Returning Pointers from Functions
• Functions can return pointers, but you must
be sure the object the pointer references still
exists.
• You should only return a pointer from a
function if it is:
– A pointer to an object that was passed into the
function as an argument.
– A pointer to a dynamically allocated object.
Starting Out with C++, 3rd Edition
53
Polymorphism
Polymorphism means more than one form, same object
performing different operations according to the
requirement.
Polymorphism can be achieved by using two ways,
those are
1. Method overriding
2. Method overloading
Method overloading means writing two or more
methods in the same class by using same method
name, but the passing parameters is different.
Method overriding means we use the method names in
the different classes, that means parent class method is
used in the child class.
Starting Out with C++, 3rd Edition
54
Starting Out with C++, 3rd Edition
55
Virtual Function
A virtual function a member function which is declared
within base class and is re-defined (Overriden) by
derived class.
When you refer to a derived class object using a
pointer or a reference to the base class, you can call a
virtual function for that object and execute the derived
class’s version of the function.
Starting Out with C++, 3rd Edition
56
Virtual Function
•Virtual functions ensure that the correct
function is called for an object, regardless of
the type of reference (or pointer) used for
function call.
•They are mainly used to achieve Runtime
polymorphism
•Functions are declared with
a virtual keyword in base class.
•The resolving of function call is done at
Run-time.
Starting Out with C++, 3rd Edition
57
Rules for Virtual Functions
1. They Must be declared in public section of class.
2. Virtual functions cannot be static and also cannot
be a friend function of another class.
3. Virtual functions should be accessed using pointer
or reference of base class type to achieve run time
polymorphism.
4. The prototype of virtual functions should be same in
base as well as derived class.
5. They are always defined in base class and
overridden in derived class. It is not mandatory for
derived class to override (or re-define the virtual
function), in that case base class version of function
is used.
6. A class may have virtual destructor but it cannot
have a virtual constructor.
Starting Out with C++, 3rd Edition
58
C++ Abstract class
•Abstract classes are the base class
which cannot be instantiated.
•A class containing pure virtual function is
known as abstract class.
Starting Out with C++, 3rd Edition
59
Function overriding
Inheritance allows software developers to derive a new
class from the existing class. The derived class inherits
features of the base class (existing class).
Suppose, both base class and derived class have a
member function with same name and arguments
(number and type of arguments).
If you create an object of the derived class and call the
member function which exists in both classes (base
and derived), the member function of the derived class
is invoked and the function of the base class is ignored.
Starting Out with C++, 3rd Edition
60
Function overriding
.
Starting Out with C++, 3rd Edition
61
How to access the overridden function in
the base class from the derived class?
Starting Out with C++, 3rd Edition
62
Examples of virtual function
#include<iostream>
using namespace std;
class base
{
public:
virtual void print ()
{ cout<< "print base class" <<endl; }
void show ()
{ cout<< "show base class" <<endl; }
};
class derived:public base
{
public:
void print ()
{ cout<< "print derived class" <<endl; }
void show ()
{ cout<< "show derived class" <<endl; }
};
int main()
{
base *bptr;
derived d;
bptr = &d;
//virtual function, binded at runtime
bptr->print();
// Non-virtual function, binded at compile time
bptr->show();
}
Starting Out with C++, 3rd Edition
63
Static Binding
The reason for the incorrect output is that the
call of the function area() is being set once by
the compiler as the version defined in the base
class. This is called static resolution of the
function call, or static linkage - the function call
is fixed before the program is executed. This is
also sometimes called early binding because
the area() function is set during the compilation
of the program.
Starting Out with C++, 3rd Edition
64
Dynamic Binding
C++ provides facility to specify that the compiler
should match function calls with the correct
definition at the run time; this is called dynamic
binding or late binding or run-
time binding. Dynamic binding is achieved
using virtual functions. Base class pointer points
to derived class object.
Starting Out with C++, 3rd Edition
65
Function overloading
Overloading a method (or function) in C++ is the ability for functions
of the same name to be defined as long as these methods have
different signatures (different set of parameters). Method overriding
is the ability of the inherited class rewriting the virtual method of the
base class.
a) In overloading, there is a relationship between methods
available in the same class whereas in overriding, there is
relationship between a superclass method and subclass method.
(b) Overloading does not block inheritance from the superclass
whereas overriding blocks inheritance from the superclass.
(c) In overloading, separate methods share the same name
whereas in overriding, subclass method replaces the superclass.
(d) Overloading must have different method signatures whereas
overriding must have same signature.
Starting Out with C++, 3rd Edition
66
Function overriding
Overriding means, giving a different definition of an existing
function with same parameters, and overloading means adding a
different definition of an existing function with different parameters.
1.Function Overloading is when multiple function with same name
exist in a class. Function Overriding is when function have same
prototype in base class as well as derived class.
2.Function Overloading can occur without inheritance. Function
Overriding occurs when one class is inherited from another class.
3.Overloaded functions must differ in either number of parameters
or type of parameters should be different. In Overridden function
parameters must be same.

Pointer

  • 1.
    Starting Out withC++, 3rd Edition 1 POINTERS
  • 2.
    Starting Out withC++, 3rd Edition 2 Introduction of Pointer • Pointers are variables which holds the the address of other variables. • Pointer variables are denoted by ‘*ptr’ • Pointers are the derived data type
  • 3.
    Starting Out withC++, 3rd Edition 3 Introduction of Pointer #include <iostream> using namespace std; int main() { int var1 = 3; int var2 = 24; int var3 = 17; cout << &var1 << endl; cout << &var2 << endl; cout << &var3 << endl; }
  • 4.
    Starting Out withC++, 3rd Edition 4 1200 1201 1203 letter number amount
  • 5.
    Starting Out withC++, 3rd Edition 5 // This program uses the & operator to determine a variable’s // address and the sizeof operator to determine its size. #include <iostream.h> void main(void) { int x = 25; cout << "The address of x is " << &x << endl; cout << "The size of x is " << sizeof(x) << " bytesn"; cout << "The value in x is " << x << endl; }
  • 6.
    Starting Out withC++, 3rd Edition 6 Program Output The address of x is 0x8f05 The size of x is 2 bytes The value in x is 25
  • 7.
    Starting Out withC++, 3rd Edition 7 Pointer Variables • Pointer variables, which are often just called pointers, are designed to hold memory addresses. With pointer variables you can indirectly manipulate data stored in other variables.
  • 8.
    Starting Out withC++, 3rd Edition 8 Pointers are useful for the following: • Working with memory locations that regular variables don’t give you access to • Working with strings and arrays • Creating new variables in memory while the program is running • Creating arbitrarily-sized lists of values in memory
  • 9.
    Starting Out withC++, 3rd Edition 9 // This program stores the address of a variable in a pointer. #include <iostream.h> void main(void) { int x = 25; int *ptr; ptr = &x; // Store the address of x in ptr cout << "The value in x is " << x << endl; cout << "The address of x is " << ptr << endl; }
  • 10.
    Starting Out withC++, 3rd Edition 10 Program Output The value in x is 25 The address of x is 0x7e00
  • 11.
    Starting Out withC++, 3rd Edition 11 0x7e00 25 ptr x Address of x: 0x7e00
  • 12.
    Starting Out withC++, 3rd Edition 12 Program 9-3 // This program demonstrates the use of the indirection // operator. #include <iostream.h> void main(void) { int x = 25; int *ptr; ptr = &x; // Store the address of x in ptr cout << "Here is the value in x, printed twice:n"; cout << x << " " << *ptr << endl; *ptr = 100; cout << "Once again, here is the value in x:n"; cout << x << " " << *ptr << endl; }
  • 13.
    Starting Out withC++, 3rd Edition 13 Program Output Here is the value in x, printed twice: 25 25 Once again, here is the value in x: 100 100
  • 14.
    Starting Out withC++, 3rd Edition 14 #include <iostream> void main(void) { int x = 25, y = 50, z = 75; int *ptr; cout << "Here are the values of x, y, and z:n"; cout << x << " " << y << " " << z << endl; ptr = &x; // Store the address of x in ptr *ptr *= 2; // Multiply value in x by 2 ptr = &y; // Store the address of y in ptr *ptr *= 2; // Multiply value in y by 2 ptr = &z; // Store the address of z in ptr *ptr *= 2; // Multiply value in z by 2 cout << "Once again, here are the values of x, y, and z:n"; cout << x << " " << y << " " << z << endl; }
  • 15.
    Starting Out withC++, 3rd Edition 15 Program Output Here are the values of x, y, and z: 25 50 75 Once again, here are the values of x, y , and z: 50 100 150
  • 16.
    Starting Out withC++, 3rd Edition 16 Relationship Between Arrays and Pointers • array names can be used as pointers, and vice-versa.
  • 17.
    Starting Out withC++, 3rd Edition 17 // This program shows an array name being dereferenced // with the * operator. #include <iostream.h> void main(void) { short numbers[] = {10, 20, 30, 40, 50}; cout << "The first element of the array is "; cout << *numbers << endl; }
  • 18.
    Starting Out withC++, 3rd Edition 18 Program Output The first element in the array is 10
  • 19.
    Starting Out withC++, 3rd Edition 19 numbers numbers[0] numbers[1] numbers[2] numbers[3] numbers[4]
  • 20.
    Starting Out withC++, 3rd Edition 20 numbers numbers[0] numbers[1] numbers[2] numbers[3] numbers[4] (numbers+1) (numbers+2) (numbers+3) (numbers+4)
  • 21.
    Starting Out withC++, 3rd Edition 21 // This program processes the contents of an array. Pointer // notation is used. #include <iostream.h> void main(void) { int numbers[5]; cout << "Enter five numbers: "; for (int count = 0; count < 5; count++) cin >> *(numbers + count); cout << "Here are the numbers you entered:n"; for (int count = 0; count < 5; count++) cout << *(numbers + count)<< " "; cout << endl; }
  • 22.
    Starting Out withC++, 3rd Edition 22 Program Output with Example Input Enter five numbers: 5 10 15 20 25 [Enter] Here are the numbers you entered: 5 10 15 20 25
  • 23.
    Starting Out withC++, 3rd Edition 23 // This program uses subscript notation with a pointer and // pointer notation with an array name. #include <iostream.h> void main(void) { float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0}; float *floatPtr; // Pointer to a float int count; // array index floatPtr = coins; // floatPtr now points to coins array cout.precision(2); cout << "Here are the values in the coins array:n";
  • 24.
    Starting Out withC++, 3rd Edition 24 Program continues for (count = 0; count < 5; count++) cout << floatPtr[count] << " "; cout << "nAnd here they are again:n"; for (count = 0; count < 5; count++) cout << *(coins + count) << " "; cout << endl; }
  • 25.
    Starting Out withC++, 3rd Edition 25 Program Output Here are the values in the coins array: 0.05 0.1 0.25 0.5 1 And here they are again: 0.05 0.1 0.25 0.5 1
  • 26.
    Starting Out withC++, 3rd Edition 26 // This program uses the address of each element in the array. #include <iostream.h> #include <iomanip.h> void main(void) { float coins[5] = {0.05, 0.1, 0.25, 0.5, 1.0}; float *floatPtr; // Pointer to a float int count; // array index cout.precision(2); cout << "Here are the values in the coins array:n";
  • 27.
    Starting Out withC++, 3rd Edition 27 Program continues for (count = 0; count < 5; count++) { floatPtr = &coins[count]; cout << *floatPtr << " "; } cout << endl; }
  • 28.
    Starting Out withC++, 3rd Edition 28 Program Output Here are the values in the coins array: 0.05 0.1 0.25 0.5 1
  • 29.
    Starting Out withC++, 3rd Edition 29 Pointer Arithmetic • Some mathematical operations may be performed on pointers. – The ++ and – operators may be used to increment or decrement a pointer variable. – An integer may be added to or subtracted from a pointer variable. This may be performed with the +, - +=, or -= operators. – A pointer may be subtracted from another pointer.
  • 30.
    Starting Out withC++, 3rd Edition 30 // This program uses a pointer to display the contents // of an integer array. #include <iostream.h> void main(void) { int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int *nums, index; nums = set; cout << "The numbers in set are:n"; for (index = 0; index < 8; index++) { cout << *nums << " "; nums++; }
  • 31.
    Starting Out withC++, 3rd Edition 31 Program continues cout << "nThe numbers in set backwards are:n"; for (index = 0; index < 8; index++) { nums--; cout << *nums << " "; } }
  • 32.
    Starting Out withC++, 3rd Edition 32 Program Output The numbers in set are: 5 10 15 20 25 30 35 40 The numbers in set backwards are: 40 35 30 25 20 15 10 5
  • 33.
    Starting Out withC++, 3rd Edition 33 Initializing Pointers • Pointers may be initialized with the address of an existing object.
  • 34.
    Starting Out withC++, 3rd Edition 34 Comparing Pointers • If one address comes before another address in memory, the first address is considered “less than” the second. C++’s relational operators maybe used to compare pointer values.
  • 35.
    Starting Out withC++, 3rd Edition 35 0x5A00 array[0] array[1] array[2] array[3] array[4] 0x5A04 0x5A08 0x5A0C 0x5A0F (Addresses) An array of five integers
  • 36.
    Starting Out withC++, 3rd Edition 36 Program 9-10 // This program uses a pointer to display the contents // of an integer array. #include <iostream.h> void main(void) { int set[8] = {5, 10, 15, 20, 25, 30, 35, 40}; int *nums = set; // Make nums point to set cout << "The numbers in set are:n"; cout << *nums << " "; // Display first element while (nums < &set[7]) { nums++; cout << *nums << " "; }
  • 37.
    Starting Out withC++, 3rd Edition 37 Program continues cout << "nThe numbers in set backwards are:n"; cout << *nums << " "; // Display last element while (nums > set) { nums--; cout << *nums << " "; } }
  • 38.
    Starting Out withC++, 3rd Edition 38 Program Output The numbers in set are: 5 10 15 20 25 30 35 40 The numbers in set backwards are: 40 35 30 25 20 15 10 5
  • 39.
    Starting Out withC++, 3rd Edition 39 Pointers as Function Parameters • A pointer can be used as a function parameter. It gives the function access to the original argument, much like a reference parameter does.
  • 40.
    Starting Out withC++, 3rd Edition 40 // This program uses two functions that accept addresses of // variables as arguments. #include <iostream.h> // Function prototypes void getNumber(int *); void doubleValue(int *); void main(void) { int number; getNumber(&number) // Pass address of number to getNumber doubleValue(&number); // and doubleValue. cout << "That value doubled is " << number << endl; }
  • 41.
    Starting Out withC++, 3rd Edition 41 Program continues // Definition of getNumber. The parameter, Input, is a pointer. // This function asks the user for a number. The value entered // is stored in the variable pointed to by Input. void getNumber(int *input) { cout << "Enter an integer number: "; cin >> *input; } // Definition of doubleValue. The parameter, val, is a pointer. // This function multiplies the variable pointed to by val by // two. void doubleValue(int *val) { *val *= 2; }
  • 42.
    Starting Out withC++, 3rd Edition 42 Program Output with Example Input Enter an integer number: 10 [Enter] That value doubled is 20
  • 43.
    Starting Out withC++, 3rd Edition 43 // This program demonstrates that a pointer may be used as a // parameter to accept the address of an array. Either subscript // or pointer notation may be used. #include <iostream.h> #include <iomanip.h> // Function prototypes void getSales(float *); float totalSales(float *); void main(void) { float sales[4]; getSales(sales); cout.precision(2);
  • 44.
    Starting Out withC++, 3rd Edition 44 Program continues cout.setf(ios::fixed | ios::showpoint); cout << "The total sales for the year are $"; cout << totalSales(sales) << endl; } // Definition of getSales. This function uses a pointer to accept // the address of an array of four floats. The function asks the // user to enter the sales figures for four quarters, and stores // those figures in the array. (The function uses subscript // notation.) void getSales(float *array) { for (int count = 0; count < 4; count++) { cout << "Enter the sales figure for quarter "; cout << (count + 1) << ": "; cin >> array[count]; } }
  • 45.
    Starting Out withC++, 3rd Edition 45 Program continues // Definition of totalSales. This function uses a pointer to // accept the address of an array of four floats. The function // gets the total of the elements in the array and returns that // value. (Pointer notation is used in this function.) float totalSales(float *array) { float sum = 0.0; for (int count = 0; count < 4; count++) { sum += *array; array++; } return sum; }
  • 46.
    Starting Out withC++, 3rd Edition 46 Program Output with Example Input Enter the sales figure for quarter 1: 10263.98 [Enter] Enter the sales figure for quarter 2: 12369.69 [Enter] Enter the sales figure for quarter 3: 11542.13 [Enter] Enter the sales figure for quarter 4: 14792.06 [Enter] The total sales for the year are $48967.86
  • 47.
    Starting Out withC++, 3rd Edition 47 Focus on Software Engineering: Dynamic Memory Allocation • Variables may be created and destroyed while a program is running. • A pointer than contains the address 0 is called a null pointer. • Use the new operator to dynamically allocate memory. • Use delete to dynamically deallocate memory.
  • 48.
    Starting Out withC++, 3rd Edition 48 // This program totals and averages the sales figures for any // number of days. The figures are stored in a dynamically // allocated array. #include <iostream.h> #include <iomanip.h> void main(void) { float *sales, total = 0, average; int numDays; cout << "How many days of sales figures do you wish "; cout << "to process? "; cin >> numDays; sales = new float[numDays]; // Allocate memory
  • 49.
    Starting Out withC++, 3rd Edition 49 Program continues if (sales == NULL) // Test for null pointer { cout << "Error allocating memory!n"; return; } // Get the sales figures from the user cout << "Enter the sales figures below.n"; for (int count = 0; count < numDays; count++) { cout << "Day " << (count + 1) << ": "; cin >> sales[count]; } // Calculate the total sales for (count = 0; count < numDays; count++) { total += sales[count]; }
  • 50.
    Starting Out withC++, 3rd Edition 50 Program continues // Calculate the average sales per day average = total / numDays; // Display the results cout.precision(2); cout.setf(ios::fixed | ios::showpoint); cout << "nnTotal sales: $" << total << endl; cout << "average sales: $" << average << endl; // Free dynamically allocated memory delete [] sales; }
  • 51.
    Starting Out withC++, 3rd Edition 51 Program Output with Example Input How many days of sales figures do you wish to process? 5 [Enter] Enter the sales figures below. Day 1: 898.63 [Enter] Day 2: 652.32 [Enter] Day 3: 741.85 [Enter] Day 4: 852.96 [Enter] Day 5: 921.37 [Enter] total sales: $4067.13 average sales: $813.43
  • 52.
    Starting Out withC++, 3rd Edition 52 Focus on Software Engineering: Returning Pointers from Functions • Functions can return pointers, but you must be sure the object the pointer references still exists. • You should only return a pointer from a function if it is: – A pointer to an object that was passed into the function as an argument. – A pointer to a dynamically allocated object.
  • 53.
    Starting Out withC++, 3rd Edition 53 Polymorphism Polymorphism means more than one form, same object performing different operations according to the requirement. Polymorphism can be achieved by using two ways, those are 1. Method overriding 2. Method overloading Method overloading means writing two or more methods in the same class by using same method name, but the passing parameters is different. Method overriding means we use the method names in the different classes, that means parent class method is used in the child class.
  • 54.
    Starting Out withC++, 3rd Edition 54
  • 55.
    Starting Out withC++, 3rd Edition 55 Virtual Function A virtual function a member function which is declared within base class and is re-defined (Overriden) by derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function.
  • 56.
    Starting Out withC++, 3rd Edition 56 Virtual Function •Virtual functions ensure that the correct function is called for an object, regardless of the type of reference (or pointer) used for function call. •They are mainly used to achieve Runtime polymorphism •Functions are declared with a virtual keyword in base class. •The resolving of function call is done at Run-time.
  • 57.
    Starting Out withC++, 3rd Edition 57 Rules for Virtual Functions 1. They Must be declared in public section of class. 2. Virtual functions cannot be static and also cannot be a friend function of another class. 3. Virtual functions should be accessed using pointer or reference of base class type to achieve run time polymorphism. 4. The prototype of virtual functions should be same in base as well as derived class. 5. They are always defined in base class and overridden in derived class. It is not mandatory for derived class to override (or re-define the virtual function), in that case base class version of function is used. 6. A class may have virtual destructor but it cannot have a virtual constructor.
  • 58.
    Starting Out withC++, 3rd Edition 58 C++ Abstract class •Abstract classes are the base class which cannot be instantiated. •A class containing pure virtual function is known as abstract class.
  • 59.
    Starting Out withC++, 3rd Edition 59 Function overriding Inheritance allows software developers to derive a new class from the existing class. The derived class inherits features of the base class (existing class). Suppose, both base class and derived class have a member function with same name and arguments (number and type of arguments). If you create an object of the derived class and call the member function which exists in both classes (base and derived), the member function of the derived class is invoked and the function of the base class is ignored.
  • 60.
    Starting Out withC++, 3rd Edition 60 Function overriding .
  • 61.
    Starting Out withC++, 3rd Edition 61 How to access the overridden function in the base class from the derived class?
  • 62.
    Starting Out withC++, 3rd Edition 62 Examples of virtual function #include<iostream> using namespace std; class base { public: virtual void print () { cout<< "print base class" <<endl; } void show () { cout<< "show base class" <<endl; } }; class derived:public base { public: void print () { cout<< "print derived class" <<endl; } void show () { cout<< "show derived class" <<endl; } }; int main() { base *bptr; derived d; bptr = &d; //virtual function, binded at runtime bptr->print(); // Non-virtual function, binded at compile time bptr->show(); }
  • 63.
    Starting Out withC++, 3rd Edition 63 Static Binding The reason for the incorrect output is that the call of the function area() is being set once by the compiler as the version defined in the base class. This is called static resolution of the function call, or static linkage - the function call is fixed before the program is executed. This is also sometimes called early binding because the area() function is set during the compilation of the program.
  • 64.
    Starting Out withC++, 3rd Edition 64 Dynamic Binding C++ provides facility to specify that the compiler should match function calls with the correct definition at the run time; this is called dynamic binding or late binding or run- time binding. Dynamic binding is achieved using virtual functions. Base class pointer points to derived class object.
  • 65.
    Starting Out withC++, 3rd Edition 65 Function overloading Overloading a method (or function) in C++ is the ability for functions of the same name to be defined as long as these methods have different signatures (different set of parameters). Method overriding is the ability of the inherited class rewriting the virtual method of the base class. a) In overloading, there is a relationship between methods available in the same class whereas in overriding, there is relationship between a superclass method and subclass method. (b) Overloading does not block inheritance from the superclass whereas overriding blocks inheritance from the superclass. (c) In overloading, separate methods share the same name whereas in overriding, subclass method replaces the superclass. (d) Overloading must have different method signatures whereas overriding must have same signature.
  • 66.
    Starting Out withC++, 3rd Edition 66 Function overriding Overriding means, giving a different definition of an existing function with same parameters, and overloading means adding a different definition of an existing function with different parameters. 1.Function Overloading is when multiple function with same name exist in a class. Function Overriding is when function have same prototype in base class as well as derived class. 2.Function Overloading can occur without inheritance. Function Overriding occurs when one class is inherited from another class. 3.Overloaded functions must differ in either number of parameters or type of parameters should be different. In Overridden function parameters must be same.