0

I'm totally new to cpp but know some python. I want to create a class which has an array as an attribute with size given in the constructor. Here is what I want to do but in python:

class test:
    def __init__(self,size):
        self.arr = [x for x in range(size)]

This is what I have in c++:

class Field{
public:
    int width;
    int height;
    int field[];
    Field(int _width, int _height){
        width = _width;
        height = _height;
        field = new int[width*height];
    }
};

But when declaring the field I need to provide a size, but the size is only given later. How can I do this?

2 Answers 2

2

Declare field as pointer:

int *field;

In your constructor, you were already doing dynamic allocation to the pointer (which is wrong with your previous array declaration):

field = new int[width * height];

Don't forget to delete the dynamic memory allocated in the destructor's definition.

Normal suggestion is to use C++11's arrays #include <array> or vectors (#include <vector>).

Sign up to request clarification or add additional context in comments.

Comments

0

Take field as an int * to point it to dynamically allocated memory. Make sure to free it in the destructor.

Or

Better to take a vector and reserve the memory equal to width * height as shown in below code.

class Field{
public:
    int width;
    int height;
    int *field;
    vector<int> v;
    Field(int _width, int _height){
        width = _width;
        height = _height;
        field = new int[width*height];
        v.reserve(width * height);
    }
    ~Field(){
        delete []Field;
    }
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.