const data members

If you want to make a data member of class to be constant data member, then you can use the const keyword before its data member declaration.

The const data members must be initialized by constructor in initialization List otherwise compiler throw an error. Once initialized, const data member value cannot be changed.

Example:
When we create a class of stack, we want to limit the number of entries for stack object. For that, we can use one const data member which can be used for validating the stack full scenario.

class stack
{
private:
    const unsigned int MAX_LIMIT;
    unsigned int arr[100];
    int top;
public:
    stack():MAX_LIMIT(100)
    {
         top = -1;
    }
    ~stack()
    {
         top = -1;
    }
    void push(unsigned int data)
    {
        if ((top + 1)>= MAX_LIMIT)
        {
            cout << “Stack is full” << endl;
            return;
        }
        arr[++top] = data;
    }
    int pop()
    {
        if (top <= -1)
        {
            return -1;
        }
        return arr[top--];
    }
   
    bool isEmpty()
    {         return (top == -1);
    }

    void display()
    {
        while(top)
        {
            cout << "Element: " << arr[top--] << endl;
        }
    }
};

when we use const data member, we increase the size of the object. Also, we cannot use it for setting the array size. To overcome this, instead of using a const, we can use enum.

class stack
{
private:
    enum {
    MAX_LIMIT = 100
    };
    unsigned int arr[MAX_LIMIT];
    int top;
public:
    stack()
    {
         top = -1;
    }
    ~stack()
    {
         top = -1;
    }
    void push(unsigned int data)
    {
        if ((top + 1)>= MAX_LIMIT)
        {
            cout << “Stack is full” << endl;
            return;
        }
        arr[++top] = data;
    }
    int pop()
    {
        if (top <= -1)
        {
            return -1;
        }
        return arr[top--];
    }
   
    bool isEmpty()
    {         return (top == -1);
    }

    void display()
    {
        while(top)
        {
            cout << "Element: " << arr[top--] << endl;
        }
    }
};

Advantages:

  • No need to initialize in the constructor.
  • enum can be used for array size as well.
  • Object size will not increase.

Related posts