Class + Vector (OOP problem)

Im new to oop and vector. This is what im experimenting, but I've got a runtime error instead. I would like to know what to do to fix this. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#include <iostream>
#include <string>
#include <vector>
using namespace std;

class Menu{
    vector <Menu> menu_id;
    double menu_price;
 public:
     Menu(): menu_price(0){
        cout<<"Menu list\n";
     }
     void setMenuPrice(double menu_price) {
         this->menu_price=menu_price;
         }
     double getMenuPrice() {
         return menu_price;
         }
     void display(){
        menu_id[1].setMenuPrice(5.00);
        menu_id[2].setMenuPrice(6.00);
        for(int n; n<4; n++){
            cout<<menu_id[n].getMenuPrice()<<endl;
        }
    }
};


int main(){
    Menu m;
    m.display();
}
closed account (49iURXSz)
Shouldn't your vector on this line:

7.vector <Menu> menu_id;

...be using an integer?

7.vector <int> menu_id;

It appears you're trying to define a vector of Menus when you're still trying to define what a menu is in your class.
The real problem here is that in your display function:
19
20
21
void display(){
    menu_id[1].setMenuPrice(5.00);
    menu_id[2].setMenuPrice(6.00);

You're accessing indices 1 and 2 of menu_id, but nowhere have you added any elements to menu_id, so you end up going out of bounds.

Also, why does your Menu class contain a vector of Menu items? That doesn't really make sense -- it's like going to a restaurant and finding that each item on the menu is itself another menu.

Also, on line 22, you forgot to give a starting value for n.
Topic archived. No new replies allowed.