CPP - Notes PPT Pointer
CPP - Notes PPT Pointer
new Employee;
void f()
...
1
} // Memory for employee automatically reclaimed
Employee* boss;
Time* deadline;
The
types Employee* and Time* are
pointers to employee and time Figure 1 Pointers and the
objects Objects to Which They
Point
boss and deadline store
addresses
They do not store actual
employee or time objects
2
To access a value, given a pointer, you must dereference the
pointer
raise_salary(*boss, 10);
. . .
3
Employee* boss = NULL;
Employee* boss;
new type_name
new type_name(expression1, expression2, ... ,
expressionn)
Example:
new Time;
new Employee("Lin, Lisa", 68000)
Purpose:
type_name* variable_name;
type_name* variable_name = expression;
Example:
Employee* boss;
4
Product* p = new Product;
Purpose:
*pointer_expression
pointer_expression->class_member
Example:
*boss
boss->set_salary(70000)
Purpose:
Common Error
5
Employee *p, *q;(the spacing is
irrelevant)
Might be clearer to use a line for each
declaration:
Employee *p;
Employee *q;
Advanced
6
return this->score / this->price > b.score /
b.price;
}
delete pointer_expression;
Example:
delete boss;
Purpose:
Deallocate a value that is stored on the heap
and allow the memory to be reallocated.
Common Error
Dangling Pointers
A pointer that doesn't point to a valid
object
Pointer wasn't initialized, or
Object pointer referenced was reclaimed
Writing to this location may change other
variables, or your program
Reading from this location might crash
your program (if you're lucky)
This is particularly insidious:
delete boss;
string name = boss->get_name(); // NO!!
boss points to a deleted element
8
Almost impossible to catch during testing
Object appears to still be there
Location might well be claimed for something
else
Common Error
Memory Leaks
A memory block that is not deallocated is
a memory leak
Leaked memory can cause the heap to run
out of memory
Program crashes
Computer freezes up
Each new should be paired with a delete
Memory leaks should be avoided, for
memory-intensive or long-running
programs
Should be avoided for smaller programs,
too
Advanced Topic
Optional Attributes
10
receptionist points to an actual
employee, or is NULL if not needed
This is better than allocating space for an
object that might not be used.
class Department // Modeled without
pointers
{
...
private:
string name;
bool has_receptionist;
Employee receptionist;
};
Common Uses for Pointers
Object Sharing
11
Employee* receptionist;
Employee* secretary;
};
12
Employee tina("Tester,
Tina", 50000);
Department qc("Quality
Control");
qc.set_receptionist(tina
);
qc.set_secretary(tina);
tina.set_salary(55000);
Department object
now contains two
copies of Tina
Figure 4 Separate Employee
Copies are not Objects
affected by Tina's
raise
#include <string>
#include <iostream>
#include "ccc_empl.h"
/**
A department in an organization.
*/
class Department
{
public:
Department(string n);
void set_receptionist(Employee* e);
void set_secretary(Employee* e);
void print() const;
private:
string name;
Employee* receptionist;
Employee* secretary;
13
};
/**
Constructs a department with a given name.
@param n the department name
*/
Department::Department(string n)
{
name = n;
receptionist = NULL;
secretary = NULL;
}
/**
Sets the receptionist for this department.
@param e the receptionist
*/
void Department::set_receptionist(Employee* e)
{
receptionist = e;
}
/**
Sets the secretary for this department.
@param e the secretary
*/
void Department::set_secretary(Employee* e)
{
secretary = e;
}
/**
Prints a description of this department.
*/
void Department::print() const
{
cout << "Name: " << name << "\n"
<< "Receptionist: ";
if (receptionist == NULL)
cout << "None";
else
cout << receptionist->get_name() << " "
<< receptionist->get_salary();
cout << "\nSecretary: ";
if (secretary == NULL)
cout << "None";
else if (secretary == receptionist)
cout << "Same";
else
cout << secretary->get_name() << " "
<< secretary->get_salary();
cout << "\n";
}
int main()
{
Department shipping("Shipping");
14
Department qc("Quality Control");
Employee* harry = new Employee("Hacker, Harry", 45000);
shipping.set_secretary(harry);
Employee* tina = new Employee("Tester, Tina", 50000);
qc.set_receptionist(tina);
qc.set_secretary(tina);
tina->set_salary(55000);
shipping.print();
qc.print();
delete tina;
delete harry;
return 0;
}
Advanced Topic
References
You saw reference parameters.
void raise_salary(Employee& e, double by)
{
double new_salary = e.get_salary() * (1 + by / 100);
e.set_salary(new_salary);
}
16
a can be dereferenced: *a = 12; is the
same as a[0] = 12;
Pointers into arrays support pointer
arithmetic: *(a + 3) is the same as a[3]
Arrays and Pointers
18
{
if (*p > highest)
highest = *p;
p++;
count--;
}
return highest;
}
Common Error
19
if (a[i] > result[1]) result[1] =
a[i];
}
return result; // ERROR!
}
result is local to minmax
When function exits, result is gone
Advanced Topic
bigger[i] = staff[i];
delete[] staff;
staff = bigger;
staff_capacity = bigger_capacity;
21
Pointers to Character Strings
0 1 2 3 4 5
22
char* p = "Harry";
string name(p);
Common Error
23
If you're lucky, the address is not legal,
and the program crashes
If you're less lucky, the data will be
written wherever
This is a very insidious error; tough to
detect, and tough to find
It might be corrupting somebody else's
memory
Somebody else might be overwriting "your"
string
Common Error
24
char* q = p;
Two Character Pointers into the
q[0] = 'L'; // Now Same Character Array
both p and q point to
"Larry"
p and q are distinct
pointers, storing the
same address
Both refer to the
same object
Common Error (cont.)
25
Sometimes a function depends on another
function
Consider a function that prints a table of
values of the function
f(n) = n2 :
1 1
2 4
3 9
4 16
...
10 100
26
Pointers to Functions
Pointers to Functions
27
To declare the function pointer:
double (*f)(double)
28