-3

My code looks something like this:

namespace N {
    class C {
    public:
        void function1() {
            // code
        }
        
        void function2() {
            // code
        }

        C(int length) {
            int array[length] = {}
        }
    }
}

How should I make the array visible to other parts of the class (e.g. function1 and function2) without making it a global variable? I can't declare the variable in the private part of the class because I need to set the length according to the constructor input while the variable is being declared.

2 Answers2

0

Use dynamic memory allocation and store the array as a pointer.

namespace N {
    class C {
    public:
        void function1() {
            // code
        }
        
        void function2() {
            // code
        }

        C(int length) 
           : array(new int[length]) {}
        ~C() {
            delete [] array;
        }
    private:
        int* array;
    }
}

Alternatively, use std::vector instead...

#include <vector>
namespace N {
    class C {
    public:
        void function1() {
            // code
        }
        
        void function2() {
            // code
        }

        C(int length) 
           : array(length) {}

    private:
        std::vector<int> array;
    }
}
robthebloke
  • 9,331
  • 9
  • 12
0

Any C++ book would teach you:

class C {
public:
    C(int length) : array(length) {
    }
private:
    std::vector<int> array;
};
273K
  • 29,503
  • 10
  • 41
  • 64