question on template class

Hi I have a question. I am a beginner in C++.

In one of my programming assignment, we are going to make our own version of STL vector class.

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

The function uses another existing Vec class to construct a new one.
I don't quite understand about the "const T& t = T()", why can't we just use
"const T&t" ?

What is t=T()? why do we need it?
It makes the parameter optional. If you say const T& t, then the constructor requires 2 parameters: n and t.

If you say const T& t = T(), then the constructor can take 2 parameters if provided (n and t), but if only one parameter is provided (n), it will use a default value for t. That default value is equal to "T()", which is a default constructed object of whatever type T is.

Example:

1
2
Vec<int> a( 5 );  // calls ctor with n=5 and t=int()
Vec<int> a( 5, int() );  // same as above 
Last edited on
Be careful to put this default arguments only in ONE place and that its declaration.

Do not add them in its definition.

Also since you are going to work with templates you MUST put all definition in the same file as your declaration in order your compiler to find it. Inside your header file that is.
Disch, eypros, thanks for your answers~!
Topic archived. No new replies allowed.