Search code examples
c++constructordestructorcopy-constructordynamic-memory-allocation

Dynamic memory allocation in constructor


I am learning dynamic memory allocation. I have the following class where 'class A' should own a dynamically allocated array in the constructor. Also the copy constructor and destructor should be modified. This is what I have so far...

#include <iostream>
#ifndef A_HH
#define A_HH

#include "B.hh"

class A {
public:

  A() {  B *array = new B[12];}
  A(const A&) { /* Do not know what to put here..*/ }
  ~A() { delete[] array;}

private:

   //B array[12] ; <- This is the array that I have to modify so it becomes dynamic. 
   B *array;
} ;

#endif 

Solution

  • For starters your default constructor there is overriding the member variable "array" with a local variable of the same type, so you want the default constructor to look like this:

    A() { array = new B[12]; }
    

    Then the copy constructor presumably needs to deep copy the array over, but with a simple array you can't tell the arraysize at runtime. You need to either move to a smarter container (e.g. stl::vector) or store the size, but a naive copy constructor would look like this:

    A(const A& other)
    {
       array = new B[12];
       for(int i=0;i<12;i++)
       {
           array[i] = other.array[i];
       }
    }