Copy Ctor and assignment operator

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>


class base{
	int i;
	int *pointer;
//	const int constint;
public:
	base(int ii)//: constint(ii)
	{
		pointer = new int(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 =new int(*(_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
Last edited on
Hi there

If you change the assignment operator and the copy constructor so that they accept a constant reference this will compile.

I hope this helps.

Phil.
closed account (D80DSL3A)
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 .
Thanks Philip and fun2code...
Topic archived. No new replies allowed.