February 18, 2002
Reading assignment:
Deitel and Deitel - 7.3, 7.4, 7.6
-or-
Wang
Review and Warm-up
1. What is wrong with this code?
int *give_me_an_int_address();
int main()
{
int *i;
i = give_me_an_int_address();
cout << *i;
}
int *give_me_an_int_address()
{
int j=5;
return &j;
}
Ans: The function is returning a pointer to a local variable, which
disappears after we exit the function!
2. double arr[10];
double *access = arr;
output the last element of the array four ways.
double **app = &access;
output the last element of the array two more ways.
Ans: arr[9], *(arr+9), access[9], *(access+9), (*app)[9], *(*app+9)
3. Say I have a class called Complex_number, which has, among other things,
a constructor that takes two parameters (defaulted to 0) and a
function member called display().
Write code that creates a pointer to an object of this class, that
creates an object with new and initializes it to 1+i, and then
displays it.
Ans:
Complex_number *c;
c = new Complex_number(1,1);
c->display();
More on new and delete
- FooClass *fp;
fp = new FooClass(a, b, c);
This creates a new object of type FooClass, assigns the address
of this new object to fp, and calls the constructor to initialize
it with the values a,b,c
- delete fp;
This releases the space fp points to. If fp doesn't point to
dynamically allocated memory, you've made a mistake.
- FooClass *fp;
fp = new FooClass[10];
This creates an array of 10 FoClass objects
- delete [] fp;
This releases the array you've created.
Friends of classes
- Sometimes a class is so intimately connected with a function, that the class
declares it as a "friend". Friend functions can gains access to the class'
private data members
- Example
class Teeny {
friend void modify_private_value(Teeny *);
public:
Teeny(int v=0) {value = v;}
display() const {cout << value << endl;}
private:
int value;
};
void modify_private_value(Teeny *t)
{
t->value++;
}
int main()
{
Teeny tiny(10);
tiny.display();
modify_private_value(&tiny);
tiny.display();
}
- The above example also shows how member functions can be defined right inside
the class. Only do this with member functions that are very short.
- Sometimes an entire class (classone) is so intimately connected with another class
(classtwo) that classone declares classtwo as its friend. Place the declaration
friend class classtwo;
inside the declaration of classone. Now classtwo can have access to all
private members of any classone objects.
- Many people think the concept of "friends" is a corruption of one of the most
basic concepts of object-oriented programming, because it is contrary to the
idea of information hiding. Unfortunately, there are a couple of situations
that even purists can't escape. We'll see this when we overload the >> and <<
operators in Chapter 8.