dontn't copy its_age Cat's in pointer tmp

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
56
57
58
59
60
61
62
63
64
#include <iostream>
using namespace std;
int * tmp = new int(77);


class Cat
{
	public :
		Cat();
		~Cat();
		Cat(const Cat &);
		int getAge(void) const;
		void setAge(int a);
	private:
		int * its_age;	
};

Cat::Cat()
{
	cout<<"-- Cat constructor\n";
	its_age = new int;
	*its_age = 5;
//   tmp = 0;
}

Cat::~Cat()
{
	cout<<"-- Cat destructor\n";
	delete its_age;
	its_age = 0;	
}

Cat::Cat(const Cat & obj)
{
	cout<<"-- Copy constructor";
	tmp = its_age;
	//cout<<*tmp; //запис значення року
	its_age = new int;
	*its_age = obj.getAge();
		
}

void Cat::setAge(int a)
{
	*its_age = a;
}

int Cat::getAge()
const
{
	return *its_age;	
}

int main()
{
	
	Cat * murk = new Cat;
	Cat frik(*murk);
	cout<<murk->getAge()<<endl;
	delete murk;
	cout<<*tmp;
	system("pause>nul");	
}


Last edited on
Is there a question?
Here

1
2
3
4
5
6
7
8
9
Cat::Cat(const Cat & obj)
{
	cout<<"-- Copy constructor";
	tmp = its_age;
	//cout<<*tmp; //запис значення року
	its_age = new int;
	*its_age = obj.getAge();
		
}


its_age has an undefined value because it was not initialized. Maybe you meant

tmp = obj.its_age;

?
Last edited on
In copy constructor I assign tmp = its_age;//new address where its_age link to dynamic memory, and previous value will be los for to prevent it i assign address to pointer *tmp

here

1
2
3
4
cout<<"-- Copy constructor";
tmp = its_age;
its_age = new int;
*its_age = obj.getAge();


but it don't work;
Did not you understand what I wrote? One more its_age was not initialized and has an undefined value.
vlad from moscow, I understand what you wrote but its_age initialized in Constructor
1
2
3
4
5
6
7
Cat::Cat()
{
	cout<<"-- Cat constructor\n";
	its_age = new int;
	*its_age = 5;
} 


when object create execute Cat::Cat() and to pointer its_age initialized value 5.
Last edited on
vlad from moscow, I understand what you wrote but its_age initialized in Constructor


No, it isn't. Your code was in the copy constructor. Your object was not constructed with the default constructor, but with the copy constructor, where its_age is not initialized before it is assigned to tmp. [Edit: Just in case that's not clear enough, in any constructor you are dealing with a new object, not one that existed prior to the constructor being called (i.e. not an object already constructed.)]

Of course, setting a global variable that's already pointing to dynamic memory doesn't make much sense anyway. You leak the memory that tmp was pointing to.
Last edited on
Ok - object frik has no initialize its age because they are not initialized in copy constructor. How to prevent memory leak in copy constructor?
Topic archived. No new replies allowed.