1

//I have a for loop that should construct an array of a certain class "Line" from two arrays of floats

for (int i=0; i<length; i++) Linearray[i](a[i], b[i]);

//my constructor function for line is:

pine::pine(float a, float b) {
   st = a;
   e = b;
}

//the error I'm getting is that I have no call operator defined.
//It's a little complicated to explain, so say all I can use is this constructor to fill that array. //also assume arrays a and b are full of floats.

  • `std::vector Linearray; for (...) Linearray.emplace_back(a[i], b[i]);` – Daniel Langr May 17 '21 at 07:13
  • 2
    How is `Linearray` defined? Please post an [MCVE]. – KamilCuk May 17 '21 at 07:13
  • 1
    Formally speaking, *you* can't call a constructor at all. It is called on your behalf when an object is to be created. – molbdnilo May 17 '21 at 07:18
  • Please define exactly what `Linearray` is, because it matters in that context, as what you mean might be an assignment, not typical construction. – alagner May 17 '21 at 07:18
  • @molbdnilo formally you can, `Line instance; instance = Line(a,b);` would be a direct call, leading to creation of temporal object (all questions why consider this a constructor call direct to Mr. Bjarne, please). – Swift - Friday Pie May 17 '21 at 07:29

2 Answers2

4

This Linearray[i](a[i], b[i]); tries to call the call operator operator()() (see also What are C++ functors and their uses?) from the Line class (which you probably haven't defined, hence the error) at the ith element in that list. You'd need to assign a new instance to call a constructor there:

Linearray[i] = Line(a[i], b[i]);
Timo
  • 9,269
  • 2
  • 28
  • 58
0

Although your question is already answered by Timo. Here is another way to achieve same goal

#include <iostream>
using namespace std;

class Line{
  private:
    int start, end;

  public:
  Line(){}

  Line(float a, float b) {
     start = a;
     end = b;
  }

};


int main() {
  std::cout << "Hello World!\n";
  int N = 5;
  Line * arr = (Line*)malloc(sizeof(Line) * N);

  for(auto i=0; i<N; i++){
    arr[i] = Line(5,6);
  }

}
ls_da3m0ns
  • 146
  • 5