user12095096
user12095096

Reputation: 33

Defining methods and field of an Array in a class

I would like to be able to build a class where I have an array of integers. I have just made a simple code, but it's not printing the elements of the array. The code compiles, but I don't have any results.

#include <iostream>

using namespace std;

const int len = 5;

class TrialArray {
    protected:
        int len;
        int A[];
    public:
        TrialArray() {
            for (int i=0; i<this->len; i=i+1) {
                this->A[i] = i;
            }
        }
        void print() {
            for (int i=0; i<this->len; i=i+1) {
                std::cout << this->A[i] << '\t';
            }
        }
};

int main() {
    TrialArray A;
    A.print();

    return 0;
}

It's a simple code. in the main, I have the method, A.print() and it should print the values, 0,1,2,3,4 in this case but it's not. And I am not understanding where I might be doing wrong.

Upvotes: 1

Views: 47

Answers (1)

You are referencing the this->len variable in the constructor instead of the global static len.

Also you have not specified the size of the array.

You need to change your code to properly reference the global variable. A better way to do this is to provide the size of the TrialArray in the constructor.

Change the int A[] to int *A and dynamically allocate it with new. Store the size given to the constructor in this->len, and then populate the array as you have done.

Like this:

#include <iostream>

using namespace std;

class TrialArray
{
    protected:
        int len;
        int *A;
    public:
        TrialArray(int size)
        {
            A = new int[size];
            this->len = size;
            for (int i=0; i<this->len; i=i+1)
            {
                this->A[i] = i;
            }
        }
        void print() {
            for (int i=0; i<this->len; i=i+1)
            {

                std::cout << this->A[i] << '\t';
            }
        }
};

int main()
{
    TrialArray A(5);
    A.print();

    return 0;
}

Upvotes: 1

Related Questions