0

I want to test some feature of template in C++, so I write the following code in test2.cpp:

#include <iostream>

using namespace std;

class Int
{
private:
    int data;
public:
    Int(int d)
    {
        cout << "Int: Int(int d)\n";
        data = d;
    }
    // Int ()
    // {
    //     cout << "Int: Int()\n";
    //     cout << "Why do I need this?\n";
    // }
    Int (const Int& I)
    {
        cout << "Int: Int(const Int&)\n";
        data = I.toInt();
    }
    int toInt() const
    {
        return data;
    }
};

template <typename T>
class IntBox
{
private:
    T data;
public:
    IntBox(const T& t)
    {
    }

    int toInt() const
    {
        return data.toInt();
    }
};

int main(int argc, char **argv)
{
    bool b = true;
    int i = 1;

    Int I(i);

    IntBox<Int> IB(I);

    return 0;
}

Notice that I have comment out the constructor without parameter of Int. When I try to compile the with

g++ .\test2.cpp -std=c++2a -o test2.exe

It says

.\test2.cpp: In instantiation of 'IntBox<T>::IntBox(const T&) [with T = Int]':
.\test2.cpp:54:21:   required from here
.\test2.cpp:38:5: error: no matching function for call to 'Int::Int()'
   38 |     {
      |     ^
.\test2.cpp:20:5: note: candidate: 'Int::Int(const Int&)'
   20 |     Int (const Int& I)
      |     ^~~
.\test2.cpp:20:5: note:   candidate expects 1 argument, 0 provided
.\test2.cpp:10:5: note: candidate: 'Int::Int(int)'
   10 |     Int(int d)
      |     ^~~
.\test2.cpp:10:5: note:   candidate expects 1 argument, 0 provided

It pointed out that the compiling goes to IntBox<Int> IB(I);, it asks for a constructor of Int without parameter. I can't understand why this happens.

It seems wired to me since there's nothing to run in IntBox::IntBox(const Int&).

  • `IntBox` has a member variable `Int data` for which you did not provide an initializer, therefore `data` is default-constructed . To fix this, initialize `data` . – M.M Aug 17 '21 at 03:27
  • 1
    @M.M Thank you so much! I've solved this by using initialization list as you recommended. – Wenling Liu Aug 17 '21 at 08:32

0 Answers0