Using new operator in class constructor

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
#include <iostream>
using namespace std;

class numbers
{
private:
    float data;

public:
    numbers(int x) // Constructor
    {
        float new integers[x];
    }

    // Mutator Functions

    // Accessor Functions
    float getAll(int SIZE)
    {
        for (int i = 0; i < SIZE; i++)
        {
            return integers[i];
        }
    }
};

int main()
{
    int SIZE;

    cout << "How big should the array be? ";
    cin >> SIZE;
    cin.ignore();

    numbers n(SIZE);

    cout << "Array values: " << n.getAll(SIZE);

    cin.get();
    return 0;
}


I'm trying to create a constructor in my class "numbers" to dynamically allocate memory for an array of the size the user types in. Like say the user types in "20", then the class constructor would create a new array that would hold 20 floats. I don't know a lot about classes, so any help with how to do this would be appreciated.
You need to declare the internal data as a pointer so it can store a pointer to the array.

In the constructor, you need to assign the array returned by new to your data...look up the syntax on that, because you don't have it quite right.

Your get all function doesn't do what you expect. The first time the function hits return, it's over; it won't keep returning each of the values in the array.
Try this:
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
class numbers
{
private:
    float* integers;
public:
    numbers(int x) // Constructor
    {
        integers = new float[x];
    }
    ~numbers()
    {
        delete[] integers; // remember to delete after using new
    }

    // Mutator Functions

    // Accessor Functions
    float* getAll
    {
        return integers;
    }
    float* getAt(int i)
    {
        return integers[i];
    }
};
Last edited on
Topic archived. No new replies allowed.