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

#include <stdio.h>
#include <string>
#include <vector>

class Foo
   std::string _str;
      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;

Recommended Answers

All 5 Replies

It would appear that initialization of arrays like that is not allowed.

Instead of the line

Foo* f = new Foo[2]("Hello");

you have to use

Foo* f[] = {new Foo("Hello"), new Foo("Hello"));

Then for deleting, you have to iterate throgh each element of the array.

for (int i = 0; i < 2; ++i)
   delete f[i];

A better method is to use vector instead of array. Then you can have an easy initialization.

vector<Foo*> f (2, new Foo("Hello"));

>>Foo* f[] = {new Foo("Hello"), new Foo("Hello"));

Nope. That doesn't compile either. And even if it did it would not create an array of Foo structuctures.

Well you could do it like this: Foo* f[2] = {new Foo("Hello"), new Foo("Hello")}; but you'll have to delete them manually 1 item at a time:

delete f[0];
delete f[1];


Which compiler are you using? I'm using Visual Studio 2005 and the code compiles perfectly. Also, it creates an array of pointers to objects.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.