Here are a few other C++ features that are useful to know.
As an example, we could make the Full routine an inline.
class Stack {
...
bool Full() { return (top == size); };
...
};
There are two motivations for inlines: convenience and performance. If overused, inlines can make your code more confusing, because the implementation for an object is no longer in one place, but spread between the .h and .c files. Inlines can sometimes speed up your code (by avoiding the overhead of a procedure call), but that shouldn't be your principal concern as a student (rather, at least to begin with, you should be most concerned with writing code that is simple and bug free). Not to mention that inlining sometimes slows down a program, since the object code for the function is duplicated wherever the function is called, potentially hurting cache performance.
for (int i = 0; i < 10; i++) ;
Depending on your compiler, however, the variable i may still visible after the end of the for loop, however, which is not what one might expect or desire.
// and extend to
the end of the line. These are usually more handy than the
/* */ style of comments.
For example, you can declare that a member function only reads the member data, and never modifies the object:
class Stack {
...
bool Full() const; // Full() never modifies member data
...
};
As in C, you can use const to declare that a variable is never modified:
const int InitialHashTableSize = 8;
This is much better than using #define for constants, since the above is type-checked.
cout << "Hello world! This is section " << 3 << "!";
This is equivalent to the normal C code
fprintf(stdout, "Hello world! This is section %d!\n", 3);
except that the C++ version is type-safe; with printf, the compiler won't complain if you try to print a floating point number as an integer. In fact, you can use traditional printf in a C++ program, but you will get bizarre behavior if you try to use both printf and << on the same stream. Reading from stdin works the same way as writing to stdout, except using the shift right operator instead of shift left. In order to read two integers from stdin:
int field1, field2;
cin >> field1 >> field2;
// equivalent to fscanf(stdin, "%d %d", &field1, &field2);
// note that field1 and field2 are implicitly modified
In fact, cin and cout are implemented as normal C++ objects, using operator overloading and reference parameters, but (fortunately!) you don't need to understand either of those to be able to do I/O in C++.