Constructor Assignment List

When creating a constructor for some class, it has been advised to use an assignment list to initialize the member variables. This I think I understand, although not sure as to why this is so. Consider
1
2
3
4
5
6
7
class foo
{
foo() : m_var1(0), m_var2(0.0 {}
~foo();
int m_var1;
double m_var2;
} /* end foo() */


In this example we have variables of the class foo with a known time, int and double. Suppose we develop a class that is a template. How do we deal with initialization lists then? How should I address the list if the type can be string, or int, or char? Here is the same code with the template implemented.

1
2
3
4
5
6
7
8
template <typename T>
class foo
{
foo() : m_var1(0), m_var2(0.0) {}  // how to address type string in assignment list?
~foo();
T m_var1;
T m_var2;
} /* end foo() */



Thanks
In your template class the both members have the same type. So it is not clear why m_var1 is assigned 0 while m_var2 is assigned 0.0.

I think you wanted to write

1
2
3
4
5
6
7
8
9
10
template <typename T1, typename T2>
class foo
{
public:
   foo() : m_var1( T1() ), m_var2( T2() ) {}  // how to address type string in assignment list?
   ~foo();
private:
   T1 m_var1;
   T2 m_var2;
}; /* end foo() */


As for std:;string type then for each member of class type its constructor is called in order in which they are defined.
Last edited on
 
foo() : m_var1( T1() ), m_var2( T2() ) {}  // how to address type string in assignment list? 


This is EXACTLY what I was looking for. I was not sure how to address unknown types for the template and this makes sense.

You guys are great, as always.

Thanks again.
Topic archived. No new replies allowed.