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?

4
  • 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. Commented Aug 20, 2017 at 7:06
  • Some reason why you can't do it in A's constructor under the control of an if bobj[0] == nullptr)? Commented Aug 20, 2017 at 7: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 - stackoverflow.com/questions/45778336/… Commented Aug 20, 2017 at 7:08
  • Don't comment on your own question -- edit your question with any additional relevant data you have. Commented Aug 20, 2017 at 7:12

1 Answer 1

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 :-)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.