Why Not Shallow Coping

In the code below why shallow copy is not happening?
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include<iostream>

using namespace std;

 

class A{

      int *p;

      int a[5];

      public:

             A(){

                 cout<<"constructor of A"<<endl;

                 p=new int;

                 }

            void set(){

                  for(int i=0;i<5;i++)

                  {

                  cout<<"Enter "<<i+1<<" th Element:";

                  cin>>a[i];

                  }

                   }    

 

            void get(){

                  for(int i=0;i<5;i++)

                  {

                  cout<<"Enter "<<i+1<<" th Element:";

                  cout<<a[i]<<endl;

                  }

 

                  }       

            void get2(){

                  for(int i=0;i<5;i++)

                  {

                  cout<<"Enter "<<i+1<<" th Element:";

                  cout<<p[i]<<endl;

                  }

 

                  }       

            void direction (){

                 p=a;

                 get2();

                 }

            void del(){

                 delete []p;

 

                 }          

            ~A(){

                 delete p;

                 cout<<"Deleted:";

                  }    

 

      };

 

int main(){

    A obj;

    obj.set();

    obj.get();

    obj.direction();

    obj.del();

    obj.get();

 

    cout<<endl;

 

 

    system("pause");

    return 0;
}
It is happening. Note, you can't delete 'p', because you didn't allocate it with 'new' - you are trying to delete something on the stack (a[], in this case), which is a no-no. Also, I would recommend setting points to 0 (NULL, nullptr, whatever) after you delete them, and then any future use of the pointer where you aren't sure if it is valid or not should be something like
1
2
3
4
if (myPtr)
{
   myPtr->DoSomething();
}
Topic archived. No new replies allowed.