1

This is a simple question... I've been given an object with an explicit constructor, and I want to initialise an array of them inside an another constructor. What's the syntax to do that?

I have honestly tried to work it out... and I'm an experienced C++ developer, this is embarrassing!

class TestObj {
public:
  explicit TestObj(int i) {}
  TestObj(const TestObj&) = delete;
  TestObj& operator=(const TestObj&) = delete;
};

class AnotherObj {
public:
  // error: converting to ‘TestObj’ from initializer list would use explicit constructor ‘TestObj::TestObj(int)’
  AnotherObj(int i) : objs{{1}, {i}} {}

  // error: could not convert ‘i’ from ‘int’ to ‘TestObj’
  AnotherObj(int i, int j) : objs{i, j} {}

  // error: use of deleted function ‘TestObj::TestObj(const TestObj&)’
  AnotherObj(int i, int j, int k) : objs{TestObj{i}, TestObj{j}} {}

protected:
  TestObj objs[2];
};
Toby Speight
  • 27,591
  • 48
  • 66
  • 103
Nicholas Wilson
  • 9,435
  • 1
  • 41
  • 80

0 Answers0