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.

  • 1
    You can't *assign* to an array, only copy to it or set its element separately. – Some programmer dude Jul 20 '17 at 12:15
  • then how do i solve the problem i written about – Viktor Lazic Jul 20 '17 at 12:17
  • 4
    Read the last part of my comment again... Or use [`std::array`](http://en.cppreference.com/w/cpp/container/array) instead. – Some programmer dude Jul 20 '17 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. – KostasRim Jul 20 '17 at 12:25
  • Sounds like you could benefit from reading one of [these C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Ron Jul 20 '17 at 12:38
  • If the class `c` is using the array, that's probably part of the reason you're stuck. (Also see [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem) – molbdnilo Jul 20 '17 at 12:41

2 Answers2

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; });
Andriy Tylychko
  • 15,967
  • 6
  • 64
  • 112
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.

IlBeldus
  • 1,040
  • 6
  • 14