-2

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
ZethGaming
  • 17
  • 3

1 Answers1

1

The main issue you have is with:

myclass o1;
o1=myclass(vect,n);

Since your class doesn't respect the rule of three (or rule of five), when a temporary is created, it shares int *b;. Then, when the temporary is deleted, your b member is deleted.

From here, you an hack it away with:

myclass o1(vect,n); // no temporaries, less issues

Or, for the proper fix, learn about the rule of three (and five) and apply it.

Jeffrey
  • 11,063
  • 1
  • 21
  • 42