2

I`m trying to use a QVector with a custom object named RoutineItem.

But this error is given:

C:\Qt\5.2.1\mingw48_32\include\QtCore\qvector.h:265: error: no matching function for call to 'RoutineItem::RoutineItem()'

This is the RoutineItem constructor:

RoutineItem(QString Name,int Position,int Time,bool hasCountdown = false,bool fastNext = false);

If I remove all the constructor arguments I no longer get that error. How can I use QVector with a custom object that has arguments?

Scott
  • 147
  • 1
  • 4
  • 11
  • 3
    As with standard containers you'll need to provide a default constructible type for QVector. – πάντα ῥεῖ Jun 19 '14 at 11:27
  • @πάνταῥεῖ The C++11 standard containers do not require default-constructible items. The requirements places on the items are specific to how you use the container. For example, `std::list` doesn't even require copy-constructible items if you can stick to the `emplace_` instead of `push_` methods. – Kuba hasn't forgotten Monica Jun 19 '14 at 20:19
  • Possible duplicate of [No matching call to default constructor, when using QVector](https://stackoverflow.com/questions/54181249/no-matching-call-to-default-constructor-when-using-qvector) – ymoreau Jan 29 '19 at 12:36

3 Answers3

7

The problem is that QVector requires that the element has a default constructor (that is the error message about). You can define one in your class. For example:

class RoutineItem {
    RoutineItem(QString Name, int Position,
                int Time, bool hasCountdown = false,
                bool fastNext = false);
    RoutineItem();
    [..]
};

Alternatively, you can let all arguments have a default values:

class RoutineItem {
    RoutineItem(QString Name = QString(), int Position = 0,
                int Time = 0, bool hasCountdown = false,
                bool fastNext = false);
    [..]
};

Alternatively, you can construct a default value of RoutineItem and initialize all vector items by it:

RoutineItem item("Item", 0, 0);
// Create a vector of 10 elements and initialize them with `item` value
QVector<RoutineItem> vector(10, item);
vahancho
  • 20,808
  • 3
  • 47
  • 55
2

Provide the non-default arguments in QVector constructor

Example: following creates 10 RoutineItem elements with same Name, Position, Time

QVector<RoutineItem> foo(10, RoutineItem("name", 123, 100 ));
                                            ^     ^     ^
                                            |     |     |
                                            +-----+-----+-----Provide arguments
P0W
  • 46,614
  • 9
  • 72
  • 119
2

If you're willing to use C++11 and std::vector, there's no more requirement for default-constructability:

void test()
{
   class C {
   public:
      explicit C(int) {}
   };

   std::vector<C> v;
   v.push_back(C(1));
   v.push_back(C(2));
}

This code won't work pre-C++11, and it won't work with QVector.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313