Classes C++ Constructor

Hello, I am creating a class that has a private array on the heap with a constructor that takes the size of the array and initializes it on the heap. Later I have to make a deconstructor delete the space and print out free after.

In my code, I was able to heap a private array and make a deconstructor, but I don't know how to take the size of the array and initialize it on the heap.

My guess is this:
int* size = new int();




Also when you initialize size on the heap, don't you also have to delete it too? If so, where, in the code, do you do that?



Here is my code so far.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Class Student
{
     private: 
          int size;
          int* array = new int[size];
     public:
          Student(); // Constructor
          ~Student(); // Deconstructor

}

Student::Student()

{
// How do you make a constructor that takes the size of the array and initializes it on the heap
}

Student::~Student()
{
     delete[] array;
     cout << "Free!" << endl;
}
Last edited on
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
#include <iostream>

struct A
{
    int size;
    int* array = new int[size]();   // array of 0-initialized ints

    A(int array_size = 10) : size(array_size) {}

    ~A() { delete [] array; }
};

void show_data(const A& a)
{
    std::cout << "For object of type 'A' at address " << &a ;
    std::cout << "\n\tsize = " << a.size;
    std::cout << "\n\tarray = " << a.array;
    std::cout << "\n\tarray contents:\n";

    for (unsigned i = 0; i < a.size; ++i)
        std::cout << "\t\t" << i << ": " << a.array[i] << '\n';

    std::cout << '\n';
}

int main()
{
    A a;
    show_data(a);

    A b(5);
    show_data(b);
}


http://ideone.com/jwkBs0

Note that a copy constructor and assignment operator should be provided for classes such as these.

See: http://stackoverflow.com/questions/4172722/what-is-the-rule-of-three
Last edited on
Topic archived. No new replies allowed.