So i created a class along with 2 constructor, a function for print and a destructor. I tryed to create 2 objects with different values and i encountered some issues with destructor.
I wrote 2 constructors so i can create objects in 2 different ways : like this
myclass o1;
o1=myclass(..parameters..)
or like this
myclass o1(..parametters..)
When i run the code with destructor in it, my first object o1 don't get created correctly, and in some cases when it does, after i create object o2, the first object change it's parameters values and get the same elements as the second one.
What is strange, when i delete the destructor (~myclass) , the code works fine.
Also, i noticed that when i create o1 with parametered constructor like o2, it works fine again.
Why is this happening and how can i solve it ? (sorry for my bad english). Here is the code:
#include <iostream>
using namespace std;
class myclass{
private:
int a;
int *b;
public:
myclass()
{
a=0;
b=NULL;
}
myclass(int vect[100], int m){
int i;
a=m;
b=new int[a+1];
for(i=1;i<=m;++i)
b[i]=vect[i];
}
void print()
{
int i;
for(i=1;i<=a;i++)
cout << b[i] << " ";
cout << '\n';
}
~myclass()
{
delete[] b;
}
};
int main()
{
int i,vect[100],n;
cin >> n;
for(i=1;i<=n;++i)
cin >> vect[i];
myclass o1;
o1=myclass(vect,n);
o1.print();
cin >> n;
for(i=1;i<=n;++i)
cin >> vect[i];
myclass o2(vect,n);
o1.print();
return 0;
}
And here is my input:
4
5 6 7 8
6
10 11 12 13 14 15
and my output:
12058816 6 7 8
10 11 12 13