CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 5 of 5
  1. #1
    Join Date
    May 2001
    Location
    Italy
    Posts
    56

    template question..

    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.


  2. #2
    Join Date
    Apr 1999
    Posts
    27,449

    Re: template question..

    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


  3. #3
    Join Date
    May 2001
    Location
    Italy
    Posts
    56

    Re: template question..

    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) {})?



  4. #4
    Join Date
    Apr 1999
    Posts
    27,449

    Re: template question..

    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




  5. #5
    Join Date
    May 2001
    Location
    Italy
    Posts
    56

    Re: template question..

    In effect..
    Thanks a lot.
    Paolo


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured