Chris Jing
Chris Jing

Reputation: 39

How does it works when a default constructor acts as a default argument?

template <class T>
...
explicit Vec(size_type n, const T& t = T() ) { create(n, t); }

I come across this declaration in 'accelerated c++' and the 'Vec' class is simulating the behavior of 'vector' class in STL. But I don't know what will happen if I don't provide the second argument when I call this constructor. I am confused about this because I learned from the book that there is no return value of any constructor? So how can T() be used to initialize t? I a novice of C++. Could anyone elaborate relevant story to me?

Upvotes: 2

Views: 122

Answers (4)

Daniel
Daniel

Reputation: 1287

This specific statement (isolating it from the surrounding code)

const T& t = T()

creates a temporary object of type T and then the constant reference function argument t then refers to the memory location of that newly created temporary object. The constructor doesn't have a return value in the typical sense, but this procedure effectively creates and returns a new object of that type.

In brief, this is just creating a default object to copy into the vector. Notably, if your particular type T did not have a default constructor like this, then this call would fail unless you explicitly passed an object to the second argument.

Upvotes: 2

the second parameter is an default/optional parameter, that means it will be automatically assumed as T() or a new instance of T if you omit that...

examples about how optional parameters work

int myMathPowerFunction(int base, int exp = 2){

}

now, since the parameter exp is defined as optional, you could omit it when calling the function, so this myMathPowerFunction(2, 3) is as valid as myMathPowerFunction(2), considering that the compiler will put the 2nd parameter for you myMathPowerFunction(2, 2)

not in your template the optional parameter is an instance of the type T...

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 311186

If the second argument is not supplied explicitly then the compiler creates a temporary object using the default constructor T() and passes a constant reference to this temporary object as the second argument.

Upvotes: 0

cxw
cxw

Reputation: 17051

T() is an expression that creates a new instance of type T.† Therefore, T() has type T. const T& t can hold a reference to a T, and specifically can hold a reference to the thing created by T(). If you don't provide the second argument to the Vec constructor, the t will be whatever T is by default.

Upvotes: 1

Related Questions