Monday, July 27, 2009

How to declare an array of objects?

Hello,





In C++, I have a simple class called "Money". I have a default constructor and a constructor that takes a char* paramter. I want to call the non-default constructor. How do I do it?





I want to write something like:





Money m( "hello!" )[100] ;


or


Money m[100]("hello!") ;


but neither are working?





Help!

How to declare an array of objects?
Money *m[100];


for(int i=0;i%26lt;100;i++)


m[0]= new Money("hello!");





Sorry boss! u cannot use non-default constructor while using arrays in C++.
Reply:you would have to say money = {"Hello", "Hello", etc 100 times for an array of 100 length. Just use a for loop to set the object.


for( . . . )


m[i] = "Hello";





or whatever.


you could also add to the end of the array by searching for the first null or empty index and setting it to the desired input.


No comments:

Post a Comment