Classes and Objects...cont(2)

Array within a Class

Arrays can be used as data members in a class. an Array can be a private or a public data member of the class. If an array is a private data member of the class, then only the member functions of the class can access it. Otherwise if an array is a public data member of the class, it can be accessed directly using objects of the class type. Consider the following class definition:

class myarray

{

int a[20];

public;

void getval(void);

void display(void);

};

Here, the arrray a is declared as a as a private member of the class myarray. It can be accessed only through the member functions of the class like any other private data member . The member function getval() reads the values of elements of the array a and the member function display() prints the values of elements of the array a.

Constant Member Functions

If a member function of a class does not modify any data in the class, then this member function may be declared as a constant member functions using the keyword const.

int max(int, int) const;

void prn(void) const;

the qualifier const is used in both the declaration and the definition of a mamber function. Once a member function is declared constant, it cannot modify the data members of the class. the compiler will generate an error message if such functions try to modify the data values.

Friend functionsTo make an outside function friendly to a class, we can declare this function as a friend of the class shown below:

clas xyz

{

.........

.........

public;

.........

.........

friend void sum(void); //declaration of friend function

};

The function declaration is preceded by the keyword friend. A friend function, although not a member function, has full access rights to the private members of the class to which it is declared a friend.

Static Class Members

It is possible to make the vlaues of the class members constant or make class members static.

Static Data Member

A data member of a class can be declared as static. Its characteristics are:

1. It is initialized to zero when the first object of its class is created. No other initialization is allowed.

2. Only one copy of a data member is created for the entire class and is shared by all the objects of that class. It is independent of the

number of objects created.

3. It is visivle only within the class, but its life span is that of the entire program.

<type> class-name:: static-member-name

Static Member Functions

A static member function can access only othe static members declared in the same class.

A static member function can be called using the class name (instead of its objects) as follows:

class-name::function-name;

HOME LEARN C++ PREVIOUS NEXT