Jovi Zhihao Zhou Jovi Zhihao Zhou - 24 days ago 6
C++ Question

Create an array of objects, Error of no matching constructor initialization

I am trying to create an array of object BuyOrder

BuyOrder buy[10];


Why am I getting error saying "no matching constructor initialization of BuyOrder[10]"?

Below is the BuyOrder constructor. Do I have to make another default constructor?

BuyOrder::BuyOrder(double price, int quantity, Stock &s)
:buyPrice{ price },
buyQuantity{quantity},
buyStock{ s }
{}

Answer

Like I said in my comment, you can do aggregate initialization for small arrays.

#include <array>

struct example
{
    example(int, double) {}
    example(example const&) = delete;
};

int main() {

    example arr1[2] {
      {1, 3.4},
      {2, 5.6}
    };

    std::array<example, 2> arr2 {{
      {1, 3.4},
      {2, 5.6}
    }};

    return 0;
}
Comments