private member variable

What is the main purpose of private member variable? Is it to be a privately global variable in a class?
A private member is something that the user must not modify
eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
template < typename T >
class array
{
    private:
        int size;
        T *elements;
    public:
        array ( int Length ) : size ( Length )
        {
            elements = new T [ size ]; // create array
        }
        ~array()
        {
              delete[] elements;
        }
};
this example class will allocate an array using 'size' as number of elements.
If the user modifies 'size' or 'elements' without calling the class public function could lead to problems.
eg: the user delete[ ]s 'elements' and then the destructor is called => Error!
Topic archived. No new replies allowed.