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 :)
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With