0
#include<iostream>
#include<array>
#include <algorithm>
using namespace std;

class Array{
    //declaring a array
    public: int a[4];
    public: int num;
    public:
    Array() {
        //initializing a array
    a[0] = 1;
    a[1] = 2;
    a[2] = 3;
    a[3] = 4;
    }
    Array(const Array &NewObj){
      a = new int[4];

    for (int i = 0; i < 4; i++)
        a[i] = NewObj.a[i];
    }
};  

int main()
{
    cout<<" DEEP COPY : \n";
    cout<<"============ \n";
    //creating first object
    Array obj1;
    //changing value of a array at index 3
    obj1.a[3]=15;
    //declaring second object which is mapped by object 1
    Array obj2(obj1);
    
    
 cout << "Object 1: \n";
    //printing values of a array
    for(int i=0;i < (sizeof(obj1.a) / sizeof(obj1.a[0])); i++){
        cout<<obj1.a[i];
        cout << "\n";
        }
     cout << "Object 2: \n";
    for(int i=0;i < (sizeof(obj2.a) / sizeof(obj2.a[0]));i++){
        cout<<obj2.a[i];
         cout << "\n";
    }
    return 0;
}

when creating a deep copy of a variable :

 a = new int[4];

I received the error: expression must be a modifiable lvalue at this line.

The primary program's purpose is to make a deep copy of an array.

I started by defining the class and declaring an array.

Then I wrote a constructor () { [native code] } that initialises an array.

Then I wrote a copy constructor () { [native code] } in which I built a new array in which the values could be saved, but it failed with an exception about editable values.

user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    If you create the array using `int a[4];`, you don't need a custom copy constructor, since the implicitly generated one will do the right thing. But if you replace `int a[4];` with `int *a;` (don't forget to add `a = new int[4]` to the default ctor before assigning elements) - then your copy ctor starts looking right. – HolyBlackCat Mar 04 '22 at 23:16
  • 1
    `public` everywhere and that strange `new` usage makes me think that you're trying to force Java syntax into C++. This will not work. In any case, I suggest getting [a good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), it should explain how arrays work, the difference between array and pointer and how to wirte copy constructors. – Yksisarvinen Mar 04 '22 at 23:23
  • Code note: you don't have to keep saying `public:`. The first one is sufficient. Everything after it, until a different access specifier occurs, is public. – Pete Becker Mar 04 '22 at 23:23

1 Answers1

0

You can get rid of a = new int[4]. Think about why you don't need that line in the regular constructor. Do you actually need to be allocating more memory?

maxrzaw
  • 121
  • 5
  • Worth noting that an array knows how to copy itself without further assistance. No copy constructor or assignment operator is required. – user4581301 Mar 04 '22 at 23:49