I want to achieve the following behaviour:
- The class DataSequence has a pointer that points to an array in the main function.
- print the array when an object in initialised of the class DataSequence
- create a deep-copy of the same object (via a copy constructor) and print it when the object is formed.
The code I have written is as follows:
#include<bits/stdc++.h>
using namespace std;
class DataSequence{
float *ptr;
int _size;
public:
DataSequence(float input[] , int size){
_size = size;
ptr = new float; ptr = input;
//print the array
cout << "Main constructor" << endl;
for(int i=0 ; i<_size; ++i){
cout << *(ptr+i) << " ";
// ++ptr;
}
}
//copy constructor
DataSequence(DataSequence &d){
_size = d._size;
ptr = new float; *ptr = *(d.ptr);
//print the array
cout << "copy constrructor" << endl;
for(int i=0 ; i<_size ; ++i){
cout << *(ptr+i) <<" ";
// ++ptr;
}
}
};
int32_t main(){
int size=4;
float input[size];
int bins;
input[0] = 3.4;
input[1] = 1.3;
input[2] = 2.51;
input[3] = 3.24;
DataSequence d(input , size);
cout << endl;
DataSequence d1 = d;
return 0;
}
The output is as follows
Main constructor
3.4 1.3 2.51 3.24
copy constrructor
3.4 2.42451e-038 -2.61739e-019 3.20687e-041
I am unable to figure out why I am getting garbage from the copy constructor, can someone help.