How to check for shallow copy?

I know that c2 is shallow copied into c3. But how to show that to audience that it is a shallow copy rather than deep copy. I know i can't use delete to destroy contents of c2 and then print c3 nor can i use a manual destructor . It would be useful if someone can tell me how to delete object c2 so that i may show content of c3 and c2.

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
#include <iostream>
using namespace std;
////////////////////////////////////////////////////////////////
class Counter
{
protected: //NOTE: not private
unsigned int count; //count
public:
Counter() : count() //constructor, no args
{ }
Counter(int c) : count(c) //constructor, one arg
{ }
unsigned int get_count() const //return count
{ return count; }
Counter operator ++ () //incr count (prefix)
{ return Counter(++count); }
};
////////////////////////////////////////////////////////////////
class CountDn : public Counter
{
public:
CountDn() : Counter() //constructor, no args
{ }
CountDn(int c) : Counter(c) //constructor, 1 arg
{ }
CountDn operator -- () //decr count (prefix)
{ return CountDn(--count); }
};
////////////////////////////////////////////////////////////////
int main()
{
CountDn c2(100);

cout << "\nc2=" << c2.get_count(); //display

--c2; --c2; //decrement c2
cout << "\nc2=" << c2.get_count(); //display it
CountDn c3 = --c2; //create c3 from c2
cout << "\nc3=" << c3.get_count(); //display c3
cout << endl;
return 0;
}
Last edited on
You can show that c3 is a copy of c2 with

cout << c3.get_count();

which you are already doing. What exactly are you trying to demonstrate? I suspect you might be trying to show that c3 is a separate object and not the same thing as c2. In which case, this will do it:

1
2
3
4
5
6
7
CountDn c2(100);
CountDn c3 = c2;

--c2;

cout << "\nc2=" << c2.get_count(); //display c2
cout << "\nc3=" << c3.get_count(); //display c3 - different value 
Last edited on
Since class CountDn contains only plain old data, a shallow copy and a deep copy are the same thing - just a copy. So if you're trying to demonstrate the difference between shallow and deep copies, you need a different example.
a shallow copy and a deep copy are the same thing
can you tell me on which data members shallow copy do not hold same meaning as the deep copy
Shallow copy and deep copy are different for pointers. With a shallow copy, you copy the pointer itself. As a result, both the original and the copy will point to the same data. With a deep copy, you make a copy of the pointed-at data and change the pointer. So the original and the copy point to distinct data. For example (this is untested):
1
2
3
4
5
6
7
int *p1 = new int{1};
int *p2;
p2 = p1;  // shallow copy
*p1 = 3;  // *p1 and *p2 are now 3.

p2 = new int {*p1};  // deep copy
*p1 = 4;  // *p1 is 4, *p2 is still 3. 

Topic archived. No new replies allowed.