Saturday, January 31, 2009

Classes in C++

The concept of Classes in C++ can be explained by a simple example from [Stroustrup, 1980]

class stack {
char s[SIZE]; /* array of characters */
char* min; /* pointer to bottom of stack */
char* top; /* pointer to top of stack */
char* max; /* pointer to top of allocated space */
void new(); /* initialize function (constructor) */
public:
void push(char);
char pop();
};

A user-defined data type which specifies the type of class members that defines an object (rep. of a variable of the type) of the class, the set of functions that manipulate such objects, and access users have to those members.

Member functions are defined elsewhere,

char stack.pop()
{
if (top <= min) error("stack underflow");
return *(--top);
}

Objects of class stack can now be defined and used,

class stack s1, s2; /* two stack variables */
class stack *p1 = &s2; /* p1 points to s2 */
class stack *p2 = new stack; /* p2 points to stack object allocated on free store */

s1.push('h'); /* use object directly */
p1->push('h'); /* use object through pointer */

Technorati Tags: ,

del.icio.us Tags: ,

No comments:

Post a Comment