eror c2075-wont go away

im doing this example project, but i cant seem to figure out why visual studio 2008 keeps giving me error C2075-'Target of operator new()' : array initialization needs curly braces.
it says the error is on line 47


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
#include <stdio.h>
#include <string>
#include <vector>

class Foo
{
   std::string _str;
public:
   Foo(void)
   {
      printf("Foo: Void constructor\n");
      _str = "";
   }
   Foo ( const char *s )
   { 
      printf("Foo: Full constructor [%s]\n", s);
      _str = s;
   }
   Foo( const Foo& aCopy )
   {
      printf("Foo: Copy constructor\n");
      _str = aCopy._str;
   }
   virtual ~Foo()
   {
      printf("Foo: Destructor\n");
   }
   Foo operator=(const Foo& aCopy)
   {
      _str = aCopy._str;
      return *this;
   }
   std::string String()
   {
      return _str;
   }
   void setString( const char *str )
   {
      _str = str;
   }
};


int main()
{
   printf("Creating array via new\n");
   Foo *f = new Foo[2]("Hello");// line 47 
   printf("Creating array on heap\n");
   Foo f1[3];

   // Create a vector
   printf("Creating vector of foo\n");
   std::vector<Foo> fooVector;

   printf("Adding objects to vector\n");
   Foo f2;
   Foo f3;
   Foo f4;
   fooVector.insert( fooVector.end(), f2 );
   fooVector.insert( fooVector.end(), f3 );
   fooVector.insert( fooVector.end(), f4 );

   printf("Deleting array on heap\n");
   delete [] f;
}
I'm sorry, but there is no way to initialize an array, that has been allocated with new. You have to create a walk-around and initialize them yourself.

No explicit per-element initialization can be done when allocating arrays using the new operator

http://msdn.microsoft.com/en-us/library/cb6bd5ek(VS.80).aspx
You could do this, though:
1
2
3
Foo **f=new Foo*[n];
for (int i=0;i<n;i++)
    f[i]=new Foo("Hello");
Topic archived. No new replies allowed.