next up previous
Next: October 30 Up: October 25 Previous: Dynamic allocation


Classes

One early name for C++ is ``C with classes'' (there are other Cs with classes, e.g. Objective C). The ability to group data and behaviour (functions) into a class should be familiar from java, and exists in C++. Also, the ability to inherit behaviour and data from base classes exists in C++. Classes look a lot like C structures (even including the final semicolon) but

Here's a C++ stack class:
class stack
{
public:
    void push(int x);
    int pop();
    int empty();
    stack() {size = 0;}

private:
    int size;
    int a[100];
};
Notice the final semicolon!

The class stack mainly contains declarations of functions except for the constructor, stack(). Conventionally only small functions are implemented inside the class, since each instance of the class will contain in-line code for functions defined between the left and right braces. Most of the functions are defined in the namespace of the class:

bool stack::empty()
{
    return size == 0;
}



Danny Heap 2002-12-16