hi people,

i am able to make the following code work if i don't use a destructor:

#include<iostream>

using namespace std;

class CVector{

    public:
        int *x, *y;
        CVector();
        CVector operator+ (CVector);
        CVector(int,int);
//      ~CVector();


    private:

};



CVector::CVector(){

    x = new int;
    y = new int;

    *x=0;
    *y=0;
}


CVector::CVector(int a, int b){

    x = new int;
    y = new int;

    *x = a;
    *y = b;
}


CVector CVector::operator+ (CVector param){

    CVector temp;
    *(temp.x) = *x + *(param.x);
    *(temp.y) = *y + *(param.y);
    return temp;

}

/*
CVector::~CVector(){

    delete x;
    delete y;

}
*/

int main(){

    CVector a(3,1);
    CVector b(1,2);
    CVector c;

    c=a+b;
    cout << *(c.x) << ", " << *(c.y);

    return 0;

}

but when i uncomment the destructor.. i face problems.

am i missing something?

thanks.

avpy(the newbie)

i guess i figured it out...

#include<iostream>

using namespace std;

class CVector{

    public:
        int *x, *y;
        CVector();
        CVector& operator+ (const CVector &param);
        CVector(int,int);
        ~CVector();


    private:

};



CVector::CVector(){

    x = new int;
    y = new int;

    *x=0;
    *y=0;
}


CVector::CVector(int a, int b){

    x = new int;
    y = new int;

    *x = a;
    *y = b;
}


CVector& CVector::operator+ (const CVector &param){

    *(x) = *x + *(param.x);
    *(y) = *y + *(param.y);
    return *this;

}


CVector::~CVector(){

    delete x;
    delete y;

}


int main(){

    CVector a(3,1);
    CVector b(1,2);
    CVector c;

    c=a+b;
    cout << endl << *(c.x) << ", " << *(c.y) << endl << endl;

    return 0;

}

thanks.

I think the problem here is you need to also define copy constructor and operator= methods. Since you are allocating pointers in the constructor, the system provide shallow copy is not sufficient. When c has been assigned the result from temp, at destruction time temp has been destroyed, and thus destroying c results in the error.

In VC++ 2008, that did not fix the problem. See my previous comments.

When the assignment to c has completed, it's members are pointing to the same memory that a allocated. When c's destruction time comes, a has already cleaned those up.

Also, please post code using the code tags, like:

[code]

your code goes here

[/code]

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.