New object created on old in array, why?

When I create a new object with my Foobar class, it prints over the old object with the new information instead of creating a new.

Simple example of my code:
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
#include <stdlib.h>
#include <time.h>

using namespace std;

constant int MAX = 10;

class Corge
{
    public:
        string name;
        int number;
        Corge();
};

class Foobar
{
    public:
        Corge waldo[MAX];

        void create()
        {
            srand(time(0));
            int random;

            random = rand()%(1000);

            waldo[0].number = random;

            cout << "Enter name: ";
            cin  >> waldo[0].name;
        }
}

int main()
{
    int user(1);
    Foobar garply;

    do
    {
        cout << "Press 1 to create new object: ";
        cin >> user;

        switch(user)
        {
            case 1:
                graply.create();

            default:
                cout << "Program END";
        }
    }while(user == 1)
}


How do I make the program choose a "new" spot for the new object?

I tried the code above and did a quick print of all objects, and discovered that if i create a new object and name it Nick, then create another object and name it Marcus, then print them the only object remaining is Marcus on the spot where Nick should be.

The only reason I can think of is that I create all objects at waldo[0]. But I dont know what else to do?
The code posted doesn't compile.
Last edited on
- I suggest you use pointers and the new operator for each object you want to create.
..\zinjai\sin_titulo.cpp:7:1: error: 'constant' does not name a type
..\zinjai\sin_titulo.cpp:20:15: error: 'MAX' was not declared in this scope
..\zinjai\sin_titulo.cpp:34:2: error: expected ';' after class definition
..\zinjai\sin_titulo.cpp: In member function 'void Foobar::create()':
..\zinjai\sin_titulo.cpp:29:4: error: 'waldo' was not declared in this scope
..\zinjai\sin_titulo.cpp: In function 'int main()':
..\zinjai\sin_titulo.cpp:49:5: error: 'graply' was not declared in this scope
..\zinjai\sin_titulo.cpp:55:1: error: expected ';' before '}' token
..\zinjai\sin_titulo.cpp:39:9: warning: unused variable 'garply' [-Wunused-variable]


Why you post code with simple errors and ask complicated question?
"constant" isn't a keyword!

Fix those errors get this.

../zinjai/sin_titulo.cpp:17: undefined reference to `Corge::Corge()'
Last edited on
Topic archived. No new replies allowed.