0

I am new to concept of using lambda functions in C++. My aim is to initialise a static data member array of objects using lambda function. Below is my code -

#include <iostream>
class B
{
    public:
    B() {std::cout << "B Called" <<std::endl;}
    B(int y){std::cout << "B int Called" <<std::endl;}
};
class A
{
    public:
    A(){std::cout << "Called" << std::endl;}
    static B bobj[256];
};

B bobj[256] = [] () {for (int i = 0 ; i < 256; i++) { bobj[i] = new B(2)}};

int main()
{
    A a;
}

But I am getting compilation error 'ambiguous overload for ‘operator=’ (operand types are ‘B’ and ‘B*’)' and others.

How can I code a lambda function to initialise an array of objects?

Programmer
  • 8,303
  • 23
  • 78
  • 162
  • Actually I have a templated class. A class type would be passed for its creation and in it an array of its type needs to be created - the array of objects would be used for a pre designed finite available data. – Programmer Aug 20 '17 at 07:06
  • Some reason why you can't do it in `A`'s constructor under the control of an `if bobj[0] == nullptr)`? – paxdiablo Aug 20 '17 at 07:06
  • The reason is that in this case it is class B but since actually A is a templated class - it can be of any class type - https://stackoverflow.com/questions/45778336/initialise-large-static-class-array – Programmer Aug 20 '17 at 07:08
  • Don't comment on your own question -- edit your question with any additional relevant data you have. – xaxxon Aug 20 '17 at 07:12

1 Answers1

1

I think see at least one of your problems. Your definition of bobj is an array of B objects:

B bobj[256]

Yet you are trying to assign a pointer-to-B to it (by using new):

bobj[i] = new B(2)

I believe that's the cause of the error you've shown, ambiguous overload for 'operator=' (operand types are 'B' and 'B*'). The "others" you mention I can't really comment on, because you haven't shown them to us :-)

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953