Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stack(int = 10), what does this syntax mean (C++)?

Tags:

c++

template <typename Type>
class Stack
{
private:
    int stack_size;
    int array_capacity;
    Type *array;

public:
    Stack( int = 10 ); //??
    ~Stack();
    bool empty() const;
    Type top() const;
    void push( const Type & );
    Type pop();
};

template <typename Type>
Stack<Type>::Stack( int n ) :
    stack_size( 0 ),
    array_capacity( std::max(0, n) ),
    array( new Type[array_capacity] )
{
    // Empty constructor
}

This is an implementation of a stack using a one ended array, however bits of the code is confusing me. I don't understand why it says int = 10.

Please explain, thanks :)

like image 204
mr3mo Avatar asked Feb 13 '26 02:02

mr3mo


2 Answers

It's an unnamed parameter with default value of 10.

You don't need to name parameters at the declaration of a function - all the compiler cares about are types and number of parameters.

At the definition, the name is required if you wish to use the parameter inside the body.

Nota bene: It's a declaration of default constructor, because it can be called without arguments.

like image 56
jrok Avatar answered Feb 14 '26 15:02

jrok


This gives a default value to the first argument of the constructor. This also makes the class default-constructible and implicitly convertible from int. This can have some surprising effects.

struct X {
  X(int = 10) {  }
};

void foo(X) {}

int main()
{
  X x1; // works
  X x2 = 23; // works
  foo(20); // works

  return 0;
}

This seems undesirable for a stack and you should add the explicit keyword to the constructor.

like image 34
pmr Avatar answered Feb 14 '26 16:02

pmr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!