#include <iostream>
class base{
int i;
int *pointer;
// const int constint;
public:
base(int ii)//: constint(ii)
{
pointer = newint(ii);
}
~base()
{
delete pointer;
}
base & operator=(base& right)
{
pointer = right.pointer;
return *this;
}
void print()
{
std::cout<<"The Value of Pointer is : "<<*pointer;
}
base (base& _base)
{
pointer =newint(*(_base.pointer));
}
};
base passbyvalue(base _base)
{
base temp(1);
temp = _base;
return (temp); ///////Problem in return
}
int main(int argc, char* argv[])
{
base obj1(10);
base obj2(100);
obj2 = passbyvalue(obj1);
return 0;
}
I am trying to implement copy ctor and assignment operator, but i am getting error in the functiom "passbyvalue". i dont know what is wrong in my code. kindly help
Using a constant reference IS conventional practice but it's not what is causing the program to crash. OP did not specify what type of error is occurring but I get a memory violation.
This is happening because both obj1.pointer and obj2.pointer point to the same memory location. When the destructor is called for the 2nd object it tries to delete the same memory location a 2nd time.
This is a basic error. It is caused by this line in the = operator: pointer = right.pointer;// causes both pointers to point to same memory address
Change line 20 to this: *pointer = *right.pointer;// value is copied .