3

I was reading a C++ code line. I encountered a weird code line where a variable was used as a function with a 0 as its parameter!

template <class T> class Stack {
    T data[50];
    int nElements;
public:
//This line is where the variable was used like a function!
    Stack() : nElements(0){}
    void push(T elemen);
    T pop();
    int tamanho();
    int isEmpty();
};

So what does exactly mean when we have: the constructor : private variable (0){}

This code line was very weird for me! Thanks

mins
  • 6,478
  • 12
  • 56
  • 75
Amir Jalilifard
  • 2,027
  • 5
  • 26
  • 38

3 Answers3

2

This is called an initializer list

Buddy
  • 10,874
  • 5
  • 41
  • 58
2

In the initializer_list of Stacks constructor, class member nElements is initialized with a value of zero upon creation of each Stack object.

The value 0 does not have any special meaning here, other than setting the initial number of elements for the Stack to zero as soon as it gets created and is empty.

Pixelchemist
  • 24,090
  • 7
  • 47
  • 71
1

This is called an 'initializer'. It is saying to initialize the variable with the given value, and the {} indicates the body of the constructor is empty.

The other other Alan
  • 1,868
  • 12
  • 21