C++ - Initialize private array in c++ class

4112 views c++
-3

I'm having a problem of storing data into the private array in a class.

I tried to Google and didn't find any solution.

Here's my code:

Foo.h

class Foo {
private:
    int arr[10];
    double d;
public:
    Foo::Foo(double d) {
        this->d = d;
    }
    // ...
};

Foo.cpp

int main() {
    double d = 123.456;
    int array[10];
    // Getting data from user input by for-loop 10 times.

    Foo f = Foo(d);

And here's my problem -- how to save the array into the f?

Seems like using pointer (*f.arr = array;) doesn't acturally change the arr.


I tried this solution by adding

class Foo {
// ...
Public:
    Foo::Foo(int arr_, double d_) : arr_(new int[10]), d_(d) { };

But the Visual Studio 2017 says the array is not initialized.


I also tried this solution, but VS says cannot modify the array in this scope.

Please help. Thank you in advance.

answered question

Don't use arrays, use vectors.

You should ask for an array of integers in the constructor, not a single integer. And then copy all values into array. Don't use new because Foo::arr is already allocated.

1 Answer

6

#include <algorithm>  // std::copy()
#include <iterator>   // std::size()

class Foo {
private:
    int arr[10];
    double d;
public:
    Foo(double d, int *data)
    : d{ d }
    {
        std::copy(data, data + std::size(arr), arr);
    }
    // ...
};

posted this

Have an answer?

JD

Please login first before posting an answer.