0% found this document useful (0 votes)
5 views9 pages

A4-Shallow Copy and Deep Copy

This document provides an overview of shallow and deep copy constructors in object-oriented programming, particularly in C++. It explains the differences between shallow and deep copies, their applications with arrays, and the importance of creating customized copy constructors for handling dynamic data members. Additionally, it includes practical tasks and examples to reinforce the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views9 pages

A4-Shallow Copy and Deep Copy

This document provides an overview of shallow and deep copy constructors in object-oriented programming, particularly in C++. It explains the differences between shallow and deep copies, their applications with arrays, and the importance of creating customized copy constructors for handling dynamic data members. Additionally, it includes practical tasks and examples to reinforce the concepts discussed.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

Object Oriented Programming

Shallow Copy / Deep Copy


Working with Arrays

Page 26
Shallow Copy/ Deep Copy, Working With Arrays

Deep Copy / Shallow Copy and Arrays in Classes


1. Introduction
In the previous lab a very basic introduction to copy constructors was presented. The purpose of a copy constructor is
to assist in the creation of exact copy of an object when it is being created. From the perspective of a beginner this is
enough but when we investigate the concept of copying we find that the default copy constructor is not enough. Hence
we need to define our own copy constructor. In this lab the creation of a copy constructor with details about deep copy
and shallow copy will be presented.
Arrays play an important role in any program. Arrays can be used in many forms in OOP for example arrays as data
members, arrays of objects, using static and dynamic arrays and finally the relationing arrays and constructors. All
these aspects of arrays will be discussed in detail in this lab.

2. Objective of the Experiment


After completing this lab the student should be able to:
• Understand the difference between a shallow copy and deep copy constructor.
• Explain why a deep copy constructor is needed
• Program a customized copy constructor (both deep and shallow)
• Create an array of objects
• Create and initialize an array of objects.
• Create and use an array as a data member.
• Use both static and dynamic arrays in classes.

3. Concept Map

3.1. Creating a customized copy constructor

Although C++ provides you with a basic copy constructor, but still there are occasions when you need to design you
own copy constructor. Given below are some of the reasons why you might want to create a copy constructor.

• You need to copy only some of the data members to a new object.
• Your objects contain pointers.
• Your objects contain dynamic data members.
There may be other numerous reasons why you might want to create a customized copy constructor. Before you
begin you must familiarize yourself with the syntax of a copy constructor. A copy constructor always receives an
object as a parameter and hence we can extract the data from the parameterized object and place the data in the
newly created object. Presented below are the two syntax for copy constructors:

MyClass (MyClass& other ); // A copy constructor prototype for a class


called MyClass

MyClass (const MyClass& other ); //const copy constructor prototype for


class called Myclass

In the above prototypes the object which will be copied is called “other”. By writing the const keyword a copy of an
object can be created without any change to the inherent data members. Although only some of the data members can
be copied.

Page 27
Shallow Copy/ Deep Copy, Working With Arrays

3.2. Shallow Copy Constructor


A shallow copy constructor is a copying function that does a member by member copy of one object to another. The
copy constructor provided by default is a shallow copy constructor. If a class does not have any dynamic members
then only a shallow copy constructor is needed.
Consider another case in which you want to create a partial copy of an object i.e. you only want to copy some of the
static data members then we need the help of a shallow copy constructor.
class example

private:
int a;
int b;
public:
example (example & parame) //shallow copy constructor

void showall( )

example( ) //Simple constructor

a=10;
b=20;

};
int main()

example obj1;
example obj2(obj1);
obj1.showall();
obj2.showall();
return 0;

Page 28
Shallow Copy/ Deep Copy, Working With Arrays

In the above code when object obj1 is created the nullary constructor is called and hence values 10 and 20 are allocated
to data members a and b respectively. Now when object obj2 is being created obj1 is passed to the copy constructor
as an argument. While creation of obj2 control is never shifted to the basic constructor because we are attempting to
make a new object by copying.
3.3. Deep Copy Constructor
A deep copy constructor is a constructor that has been designed to handle pointers and dynamic data members.
Although a shallow copy constructor will also copy pointers but it does so in an incorrect way. Hence it is logically
wrong to use a shallow copy constructor for dynamic data members.
The problem with shallow copy constructors:
The problem with shallow copy constructors is that suppose you have a class that has a pointer as a data member and
you want to create a copy of this class object. When you call the shallow copy constructor it will copy the pointer data
member to the new object. You might think this is what we want but in fact it is wrong because copying a pointer
means that you have copied the data and the address to which the pointer is pointing. Hence you have on hand two
objects that are pointing to the same memory location. Always remember that two objects should have their own
distinct identity and distinct memory.
Memory
Copy of
Object 1 Object 1

(a)
Memory
Copy of
Object 1 Object 1

(b)

Figure 1: The effect of copy constructors on a pointer data member (a) using shallow copy (b) Using deep copy
In the code snippet below a deep copy constructor has been provided that creates a copy of a char array. The data
member len is being used to hold the length of the array.

class example
{
private:
char *str;
int len;
public:
example( ); // one normal constructor
example(char *s); // another normal constructor
example(const example &st) //Deep copy constructor
{
len = st.len;
str = new char [len + 1];
strcpy(str, st.str);
}
// other stuff
};

Page 29
Shallow Copy/ Deep Copy, Working With Arrays

When working with copy constructors it is important to remember that the copy constructor function prototype is the
same for both shallow copy and deep copy. Hence the difference lies in the fact that dynamic data members are being
handled or not. To determine if a deep copy or shallow copy constructor is being used you have to study the copy
constructor body.

3.4. Working with Arrays


As explained earlier, arrays are of very importance in every program. The main reason for their importance is that
they provide contiguous memory locations that can be accessed with a simple iterative mechanism like loops. When
it comes to classes we have many options relating to arrays. All the possibilities related to arrays are part of this lab.
Given below is a class named example that contains a simple (static) floating point array “a”. This array can be
initialized with a constructor or with a simple member function as follows.

class example

private:
float a[10]; //array as a data member
public:
example() // normal constructor

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

// put the value 0 in all locations

// other stuff
};

Given below is a class named example that contains a dynamic floating point array “a”. This array can be initialized
with a constructor or with a simple member function as follows. Since this code works with a dynamic array therefore
the size of the array can be provided at run time. In this particular code since the size is not passed there may be a
possibility that the programmer crosses the array boundary.

class example

private:
float *a; //Dynamic array as a data member
public:
example() // normal constructor

a=new //size can be passed from main to constru

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

// put the value 0 in all locations

// other stuff
};

Given below is a class named example that contains a dynamic floating point array “a”. This array can be initialized
with a constructor or with a simple member function as follows. Since this code works with a dynamic array
Page 30
Shallow Copy/ Deep Copy, Working With Arrays

therefore the size of the array can be provided at run time. In this particular code since the size is not passed there
may be a possibility that the programmer crosses the array boundary.
Another option which is very popular among programmers is that the size of the array can be stored as a data
member.

class example

private:
float *a; //Dynamic array as a data member
public:
size)

a=new float[size]; //The size is passed from the main


to the constructor

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

a[i]=0; // put the value 0 in all locations

void showall (example arr[ ], int size)


//Size is passed to restrict from crossing array boundary

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

for(int j=0; j<size; j++)

cout<<arr[i].a[j];

};

int main()

const int size=10;


obj1[size]=example(size);
//array of objects initialized with parameterized constructor
example obj2;

obj2.showall( obj1, size );


return 0;

4. Home Work Before Lab


Provided below is a statement for a program which you will code and submit to your lab instructor.

4.1 Practices from Home


Constructors of a class can be both public and private. Explain why you would create a private constructor. Create a
simple class with a single data member of your choice. Create a private constructor.
In your code demonstrate how a private constructor is called and how the object is created using a private
constructor.

Page 31
Shallow Copy/ Deep Copy, Working With Arrays

5. Procedure & Tools


5.1. Tools
Visual Studio 2012.
5.2. Setting-up Visual Studio 2012
Setup Visual Studio and make a project named “english”.
5.3. Walkthrough Task
Write a program that creates a class named “english”. The class has a string data member called sentence and another
called size that shows the number of characters of the string. Create a constructor that initializes the class objects.
Also create a copy constructor that copies the data of one object to the other.
5.4. Writing Code
In the source file created in the project “english” write the following C++ code:

class english
{
private:
string sentence;
int size;
public:
example()
{
cout<<"Enter your sentence: ";
getline(cin,sentence);
size=9;
size=sentence.length();
}
example (example & tempobj)
{
size = tempobj.size;
sentence=tempobj.sentence;
}
void showall()
{
cout<<"\nSentence: "<<sentence;
cout<<"\nCharacters: "<<size<<"\n";
} };
int main( )
{
english obj1;
english obj2=obj1;
cout<<"Object one contains data";
obj1.showall();
cout<<"Copied object contains data";
obj2.showall();
return 0;
}
Figure 1: The english class demonstrate

Figure 1: The “english” class demonstrating the use of a constructor and a copy constructor.

Page 32
Shallow Copy/ Deep Copy, Working With Arrays

5.5. Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.
5.6. Executing the Program
A sample output after running the program is shown below. Also run the code with other possible inputs.

Figure 2: Final output of “english” class

6. Practice Tasks

6.1. Practice Task 1


Lamborghini is an international luxury sports car developer stationed in Italy. The company has a reputation
for producing cars that are extremely expensive, powerful and rare. Lamborghini has developed a brand
new model called the Diablo. The company produces a very limited number of Diablo’s each year. The
company is producing the Diablo in only one colour called the “Hot Red”.
When the company has produced a Diablo, the car has a number of attributes like colour, cubic capacity,
number of seats, year of manufacture, engine number, frame number and owner name. Out of these
attributes the attributes that remain the same for all Diablo’s being produced are colour, cubic capacity and
number of seats.
Suppose you are working on a system specially designed for the Lamborghini Diablo. Follow the
instructions below for creating the class and objects:
• Store the owners name as a dynamic array data member.
• Create an object named “obj1” and initialize the object.
• Create a copy constructor that can copy all those attributes that remain the same for all cars.
• Generate another object named “obj2” that is created by copying only those attributes that are the
same from “obj1”.
• Initialize the remaining attributes with values of your own.

Page 33
Shallow Copy/ Deep Copy, Working With Arrays

6.2. Practice Task 2


Your task is to create a class that contains an integer pointer data member. Create a single object named “one” in the
main and assign values to the data member of the object. Then create another object named “two” that is a copy of
the “one”. Create a shallow copy constructor and then demonstrate that both objects share a common memory i.e.
modifying one object in fact modifies the other. Create a display function that will show the values of the object.
6.3. Outcomes
After completing this lab, students will be able to conveniently use a copy constructor in both deep copy and shallow
copy mode. Further the students will have the ability to comfortably use arrays in their various forms both inside and
outside the class.
6.4. Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Colour = Hot Red After selective copying only the permanent attributes contain
Owner = Ali Raza values.
Year of manufacture = 2013 Colour = Hot Red
Seats = 2 Owner =
Cubic Capacity = 5700 Year of manufacture =
Engine number = 123456 Seats = 2
Frame number = 987654 Cubic Capacity = 5700
Engine number =
Frame number =

Test Cases for Practice Task-2


Sample Inputs Sample Outputs
Initialize only object “one” and use it for Upon calling the display function of object “one” the modified
copying values into object “two” by using the values will be displayed
copy constructor.
Make a modification in object “two”. Upon calling the display function of object “two” the same
Call the display function of object “one”. modified values will be shown.

7. Further Reading

7.1. Books
• Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

7.2. Slides
• The slides and reading material will be provided by course instructor.

Page 34

You might also like