Hi everyone ,i wrote the following code where i a use a class to declare a friend function of overloaded operator +.Inside my class i have a pointer and although my code runs just fine when i add inside the class a deconstructor then i have a run time error.Take a look at the code:
#include<iostream>
usingnamespace std;
class one
{
public:
one(){a=newint;}
one(int k,int l){a=newint;*a=k;b=l; }
//~one(){delete a;a=NULL;} Here is the reason i have run time error
void ektiposi(){cout<<"a:"<<*a<<",b:"<<b;}
friendconst one operator+(const one& left,const one& right);
private:
int *a,b;
};
const one operator+(const one& left,const one& right)
{
one temp;
temp.b=left.b+right.b;
*temp.a=*left.a;
*temp.a+=*right.a;
return temp;
}
int main()
{
one n1(5,6),n2(4,2);
one n3;
n3=n1+n2;
n3.ektiposi();
cin.get();
return 0;
}
I guess i create a conflict in memory using ~one(){delete a;a=NULL;} but the default deconstructor does the same thing,it destroys the allocated memory,right?Thanks
#include<iostream>
usingnamespace std;
class one
{
public:
one():a(newint),b(0) {};
one(int k, int l):a(newint),b(1) { *a = k; }
~one() { delete a; a = NULL; }
void ektiposi() { std::cout << "a:" << *a << ",b:" << b; }
friendconst one operator+(const one& lhs, const one& rhs);
private:
int* a;
int b;
};
const one operator+(const one& left,const one& right)
{
one temp;
*temp.a = (*left.a + *right.a);
temp.b = (left.b + right.b);
return temp;
}
int main()
{
one n1(5,6),n2(4,2);
one n3;
n3=n1+n2;
n3.ektiposi();
cin.get();
return 0;
}
I believe the issue is because you declared both a and b as pointers inadvertently when you meant to declare one pointer and one value. The above should fix your problem as this works for me now. Let me know if you still have problems.
Your code is not a mess - I have seen far worse! :)
I apologize but I should have picked this up before - there was a second problem in your code which was on line 34. You use an assignment operator to assign the values of the unary operator to your class. As you had not specified one yourself the compiler generated one for you (it does this) which had an incorrect implementation. If you define an assignment operator for your class it solves the problem.
I have posted the code below and run it a few times to check that it works... :)
Thanks Phil,indeed the code runs just fine! The assignment operator was the missing element.I guess that when i ad the deconstructor a new conflict rises through the increment n1+n2. Maybe the element (n1+n3) which is created after the add destroys the memory of its pointer a by calling the decostructor before the assignment is passed to the element n3 .Maybe that's why the operator assignment solves this problem . Maybe,i don't know... Thanks again :)