0

I have a class of the following form:

class T
{
   public:
   /// Constructor
   T(const std::string& baseName);
};

Now within the main() method I am trying to create an array of the objects of the class using:

  T* s = new T[20](baseFileName); 

I am not getting where I am making a mistake...can someone please help.

The error which I am getting is:

error: ISO C++ forbids initialization in array new [-fpermissive]
2
  • 2
    the error you're receiving would be hard-pressed to be clearer. The language doesn't support array initialization in the fashion you're using. If you're looking for alternatives, try std::vector<T> s(20, T(baseFileName)); (which frankly, you should be using anyway rather than allowing raw pointers to own dynamic resources). Commented May 11, 2014 at 6:16
  • 1
    Look at parashift.com/c++-faq-lite/arrays-call-default-ctor.html Commented May 11, 2014 at 6:16

2 Answers 2

2

You should first create the array of objects like below:

T* s = new T[20]; //allocating 20 objects

now you can call your desired function by making a little change:

class T
{
   public:
   T(){};//default constructor
   /// Constructor
   SetValue(const std::string& baseName);
};

call the function using a loop:

for( int i=0 ; i<20;i++)
s[i].SetValue(baseString);
Sign up to request clarification or add additional context in comments.

2 Comments

This won't work, the type does not have a default constructor.
please see my code carefully, I have suggested to add a default constructor :)
2

The compiler is telling you exactly what's wrong. You can't do this:

T* s = new T[20](baseFileName);

More specifically, you can't have that (baseFileName) bit when you use new. Just add a default constructor to T and fill it in yourself. Maybe add a method to your T class that returns array for you without you having to loop every time you need to construct one.

T * s = new T[20];
for(int i = 0; i < 20; i++) { s[i].setName(baseFileName); }

Or since you already know what the array is going to look like at compile-time:

T s [20] {baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName,baseFileName, baseFileName};

1 Comment

Note that the last example will probably not do what OP needs.

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.