0
class c{};

c *ar[2];

ar = {new c, new c}; //error

"Array type is not assignable" How to assign it after declaring it, i want to do that because the class is using that variable so i just want to declare it, create a class and then assign the value, i can't assign before the class because it can't make a new c without defing the class first.

6
  • 1
    You can't assign to an array, only copy to it or set its element separately. Commented Jul 20, 2017 at 12:15
  • then how do i solve the problem i written about Commented Jul 20, 2017 at 12:17
  • 4
    Read the last part of my comment again... Or use std::array instead. Commented Jul 20, 2017 at 12:18
  • @ViktorLazic I would suggest you to study a good c++ book. SO is not here to baby spoon everyone. Google is your friend. Commented Jul 20, 2017 at 12:25
  • Sounds like you could benefit from reading one of these C++ books. Commented Jul 20, 2017 at 12:38

2 Answers 2

1

use standard library algorithm generate:

#include <algorithm>
#include <iterator>

class c{};
c* ar[2];
std::generate(std::begin(ar), std::end(ar), [] { return new c; });
Sign up to request clarification or add additional context in comments.

3 Comments

What was wrong with your previous version using std::begin and std::end? It's more readable (from begin to end), and less error prone
@KABoissonneault: godbolt.org/g/SFeaBh, GCC 7.1 failed, same error: no matching function for call to 'begin(c* [2])' with Clang 4.0, works fine with VS2015 or GCC 4.9, surprised, investigating
Try including <iterator>
0

use a loop:

for(auto i = std::begin(ar);i!=std::end(ar);++i)
    *i = new c;

this will work for (almost) all container classes, not just raw arrays.

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.