0

I am trying to create a C++ program where a user enters his choice if he wishes to add another record, and if yes then create a new object for that record.

So if I am including constructors, then how do I create a new object every time the user wants?

(If I give a predefined size to the array of object, then constructor will be called, say 50 times and initialize all 50 objects, while the user may only want to enter less). Lets just say

class grocerylist
{
    float price;
    char pname;
    public: grocerylist(){.....} //constructor
            <some code>
            .....
}

main()
{
    //grocerylist a[50]; this will call constructor 50 times! which is not desired

}

My guess here is to use the new operator inside a loop, which will break when user doesnt want to enter any more records.But the problem is, it's scope will be destroyed once it comes out of a loop.

3
  • 6
    Read about std::vector in your favorite C++ textbook. Commented Nov 9, 2014 at 4:46
  • Use a std:: vector to store your objects. To create a new grocerylist grocerylist *glist = new grocerylist(); Commented Nov 9, 2014 at 4:49
  • 1
    @Benji Or preferably grocerylist glist;. Commented Nov 9, 2014 at 4:50

1 Answer 1

2

Use std::vector and just push grocerylists. Something like:

int main() {
    std::vector<grocerylist> list;
    [...]
    while(user_wants_to_add_another_list) {
        list.push(grocerylist(...));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.