Click to See Complete Forum and Search --> : template question..


Paolo Giustinoni
April 17th, 2002, 03:54 PM
I defined a class template like this:
template <class I> class MyTemp
{
I* i;
public:
MyTemp(I j=0) { i = new I; *i = j; }
~MyTemp() { delete i; }
};
and a class B like this:
class B
{
int i;
public:
B(): i(0) {}
B(int j): i(j) {}
};
when I try to do this: MyTemp<B> b; I receive a compiler error.
Can anyone explain me why?
Thanx for every help.
Paolo.

Paul McKenzie
April 17th, 2002, 04:29 PM
What compiler error? Which compiler? I compiled this code with VC++ 6.0 and at http://www.comeaucomputing.com/tryitout/ and I did not get any errors.

template <class I> class MyTemp
{
I* i;
public:
MyTemp(I j=0) { i = new I; *i = j; }
~MyTemp() { delete i; }
};
//...
class B
{
int i;
public:
B(): i(0) {}
B(int j): i(j) {}
};
//...
int main()
{
MyTemp<B> b;
}



Regards,

Paul McKenzie

Paolo Giustinoni
April 17th, 2002, 04:46 PM
The default constructor for the class B wasn't declared.
But I don't understand why the default constructor for the template class MyTemp needs a default constructor for the class B. Isn't enough the conversion constructor (B(int) {})?

Paul McKenzie
April 17th, 2002, 05:05 PM
Simple, take a look at the template:

MyTemp(I j=0) { i = new I; *i = j; }



The highlighted code shows one place where the default constructor is necessary -- you are creating a B object with no arguments. If you leave out the default constructor, how is B supposed to be created?

Regards,

Paul McKenzie

Paolo Giustinoni
April 17th, 2002, 05:07 PM
In effect..
Thanks a lot.
Paolo