jeudi 29 septembre 2016

while calling a constructor from copy constructor it calls destructor too

I ve made a program that uses copy constructor to copy the object. In copy constructor i ve called the constructor to create memory and copy the contents. It does that successfully in constructor but immediately after the constructor ends destructor is called and i get the garbage value. At last in the main function if i make any attempts to destroy the newly created object the program crashes. why it behaves like that?

here's the code.

#include<iostream>
using namespace std;

class Test
{
    public:
    int a;
    int *p;

    Test(int a,int b,int c)
    {
        this->a=a;
        p=new int(2*sizeof(int));
        p[0]=b;
        p[1]=c;
        cout<<"\n\n "<<this->a<<"   "<<this->p[0]<<"   "<<this->p[1];
    }
    Test(const Test &ob)
    {
        Test(ob.a,ob.p[0],ob.p[1]);
        cout<<"\n\n "<<this->a<<"   "<<this->p[0]<<"   "<<this->p[1];
    }
    void print()
    {
        cout<<"\n\n\n "<<a<<"   "<<p[0]<<"   "<<p[1];
    }
    ~Test()
    {
        cout<<"\n\n\n DESTRUCTOR CALLED "<<endl;
        delete p;
    }
};

int main()
{
    Test *ob1=new Test(2,3,4);
    cout<<"\n\n\n  ob2: new object";
    Test *ob2=new Test(*ob1);
    cout<<"\n\n\n ob1";
    (*ob1).print();
    cout<<"\n\n\n ob2";
    (*ob2).print();
    delete ob1;
    delete ob2;
    return 1;
} 

produces the output:

2 3 4

ob2: new object 2 3 4

DESTRUCTOR CALLED

9968956 9968956 0

ob1

2 3 4

ob2

9968956 9968956 0

DESTRUCTOR CALLED

DESTRUCTOR CALLED

"then the program stops working i.e. crashes"....

Aucun commentaire:

Enregistrer un commentaire