mercredi 28 avril 2021

How to copy a dynamically allocated object (with having one const member of a class)

I'm trying to make a function, where user can add an entry in the data, so the array dynamically increases it's size by 1 and allows the user to enter the data.

Logic:

  1. pass the current size and array pointer by reference to a function
  2. make a new pointer array (dynamically allocated) in the function, and increase it size by 1 .
  3. copy all the data from the passed array to newly made array
  4. delete the memory allocated to parameter pointer
  5. point the parameter pointer to new pointer array.

Problem: I have a const int member in the class,following the algorithm above, when I try to copy contents to new pointer,it's obvious that id would'nt be copied to const member. I have a hunch that I can use copy constructor here with a initialization list, and initialize the new array of the function with the help of copy constructor.

I need to know how to copy a dynamically allocated object array using copy constructor and moreover, if the object have some const member.

Thanks in advance.

CLASS HEADER:

#include <iostream>
#include <stdlib.h>
using namespace std;

class ramish
{
private:
    const int id;
public:
    void print()
    {
        cout << "ID = " << id;
    }
    ramish():id(rand()%100+1)
    {
    }
    //ramish(ramish *& object)
    //{
    //}
};

FUNCTION AND DRIVER:

int main()
{
   int size = 4;
   ramish* object = new ramish[size];
   copypointer(object, size);
}

void copypointer(ramish*& object, int size)
{
   ramish *newobject = new ramish[size + 1];
   for (int i = 0; i < size; i++)
   {
       newobject[i]=object[i];
   }
   delete[]object;
   //take inps from user for newobject[size]
   object = newobject;
   newobject = NULL;
}

Aucun commentaire:

Enregistrer un commentaire