new Employee
Syntax 10.1 : new Operator new type_name
|
Syntax 10.2 : Pointer Variable Definition type_name* variable_name;
|
Time* deadline;
deadline = new Time;
Employee* boss = new Employee("Lin, Lisa", 68000);
raise_salary(*boss, 10);
string name = boss->get_name(); // abbreviation of (*boss).get_name()
string name = *boss.get_name(); // Error
string name = (*boss).get_name(); // OK
Syntax 10.3 : Pointer Dereferencing *pointer_expression
|
Employee* boss = NULL; // will set later
. . .
if (boss != NULL) name = boss->get_name(); // OK
Employee* boss = NULL;
string name = boss->get_name(); // NO!! Program will crash
void f()
{ Employee harry; // memory for employee allocated on the stack
. . .
} // memory for employee object automatically reclaimed
void g()
{ Employee* boss;
// 1-st allocation: pointer variable allocated on the stack (name boss)
boss = new Employee(. . .);
// 2-nd allocation: employee object allocated on the heap (no name!)
. . .
delete boss; // memory for employee object manually reclaimed
} // memory for boss automatically reclaimed
Syntax 10.4: delete Expression delete pointer_expression
|
Employee* boss;
string name = boss->get_name(); // NO!! boss contains a random address
delete boss;
string name = boss->get_name(); // NO!! boss points to a deleted element
class Department {
. . .
private:
string name;
Employee* receptionist;
};
class Department { // modeled without pointer
. . .
private:
string name;
bool has_receptionist;
Employee receptionist;
};
class Department {
. . .
private:
string name;
Employee* receptionist;
Employee* secretary;
};
Employee* tina = new Employee("Tester, Tina", 50000);
Department qc("Quality Control");
qc.set_receptionist(tina);
qc.set_secretary(tina);
tina->set_salary(55000);
int a[10];
int* p = a; // now p points to a[0];
*p = 12; // same as a[0] = 12;
*(a + 3) means the same as a[3]
*(a + n) means the same as a[n]
double maximum(const double a[], int a_size)
{ if (a_size == 0) return 0;
double highest = a[0];
int i;
for (i = 0; i < a_size; i++)
if (a[i] > highest) highest = a[i];
return highest;
}
double data[10];
... // Initialize data
double m = maximum(a, 10);
double maximum(const double* a, int a_size)
{ /* identical code as above yields same results */
. . .
}
char s[] = "Harry";
s[0]
s[1] s[2] s[3] s[4] s[5] 'H' 'a' 'r' 'r' 'y' '\0'
char* p = "Harry";
string name(p); // or string name = p;
string dir = . . .;
char* p = tempnam(dir.c_str(), NULL);
string file_name(p);