#### Archived

This topic is now archived and is closed to further replies.

# c++ error, vector of classes

This topic is 5643 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I have a vector of classes, and I need to initialize each one... so when I declare my vector I do apvector b(0); this declares a vector of buildings of size 0. now, when I want to initialize each one, what do i do? b.resize(1); //resize the vector b[0] = building("building name", 5); this gets an error of "Call of nonfunction" any ideas?

##### Share on other sites
Two possibilities:

1. Use an array of pointers, or...
2. Make sure your objects have a copy constructor/assignment operator and copy them into the vector.

For the latter:
class Foo{public :  //Constructor  Foo (int i)  {     m_num = i;  }  //Copy constructor  Foo (const Foo &rhs)  {    *this = rhs;  }  //Assignment operator  void operator = (const Foo &rhs)  {    m_num = rhs.m_num;  }private :  int m_num;};...std::vector <Foo> myVector;//Make enough room (not strictly necessary)myVector.reserve (15);//Add 15 objectsfor (int i = 0; i < 15; i++){   //Create new object   Foo temp (i);   //Add a copy into the vector   myVector.push_back (temp);}...

[edited by - Kippesoep on June 4, 2003 10:53:54 AM]

##### Share on other sites
b.push_back(building("building name", 5));

is more compact and efficient than

b.resize(1)
b[0] = building("building name", 5);

##### Share on other sites
Read the post more closely, guys. This is an apvector, used for the Advanced Placement tests. There is no push_back.

Now, you say you get a compile error? What''s the exact error, and on what line is it? Try initializing your array to at least a single element.

##### Share on other sites
It should still work with pointers or a copy-constructor/assignment operator, even without push_back.

1. 1
Rutin
33
2. 2
3. 3
4. 4
5. 5

• 13
• 9
• 9
• 9
• 9
• ### Forum Statistics

• Total Topics
633330
• Total Posts
3011388
• ### Who's Online (See full list)

There are no registered users currently online

×