Vous êtes sur la page 1sur 11

Lab Manual for Object Oriented Programming

(LAB-05)
Abstraction III
(Shallow Copy / Deep Copy and Working with Arrays)

Capital University of Science and Technology, Islamabad Page 41


Department of Computer Science (2017)
Lab 5 – Abstraction III

Table of Contents
1. Introduction 43

2. Activity Time boxing 43

3. Objective of the Experiment 43

4. Concept Map 43
4.1 Creating a customized copy constructor 43
4.2 Shallow Copy Constructor 44
4.3 Deep Copy Constructor 45
4.4 Working with Arrays 46

5. Home Work Before Lab 47


5.1 Practices from Home 47

6. Procedure & Tools 48


6.1 Tools 48
6.2 Setting-up Visual Studio 2008 48
6.3 Walkthrough Task 48

7. Practice Tasks 49
7.1 Practice Task 1 49
7.2 Practice Task 2 50
7.3 Outcomes 50
7.4 Testing 50

8. Evaluation Task (Unseen) 50

9. Evaluation Criteria 50

10. Further Reading 51


10.1 Books 51
10.2 Slides 51

Capital University of Science and Technology, Islamabad Page 42


Department of Computer Science (2017)
Lab 5 – Abstraction III

Lab 05: 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 relating arrays and constructors. All
these aspects of arrays will be discussed in detail in this lab.

Relevant Lecture Material

 Lectures: 8, 9, 10

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 25 mins 25 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 30 mins 30 mins
7 Practice tasks 50 + 15 (mins) 65 mins
8 Evaluation Task 45 mins 45 mins
Total Time 170 Minutes

3. 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.

4. Concept Map

4.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.
Capital University of Science and Technology, Islamabad Page 43
Department of Computer Science (2017)
Lab 5 – Abstraction III

 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.

4.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
{
a=parame.a;
b=parame.b;
}
void showall( )
{
cout<<"\na="<<a;
cout<<"\nb="<<b;
}
example( ) //Simple constructor
{
a=10;
b=20;
}
};
int main()
{
example obj1;
example obj2(obj1);
obj1.showall();
obj2.showall();
return 0;
} Capital University of Science and Technology, Islamabad Page 44
Department of Computer Science (2017)
Lab 5 – Abstraction III

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.

4.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
};
Capital University of Science and Technology, Islamabad Page 45
Department of Computer Science (2017)
Lab 5 – Abstraction III

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.

4.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++)
{
a[i]=0; // 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 float[10]; //size can be passed from main to constru

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


{
a[i]=0; // put the value 0 in all locations
}
}
// other stuff
};

Capital University of Science and Technology, Islamabad Page 46


Department of Computer Science (2017)
Lab 5 – Abstraction III

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.
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:
example(int 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;
example obj1[size]=example(size);
//array of objects initialized with parameterized constructor
example obj2;

obj2.showall( obj1, size );


return 0;
}

5. Home Work before Lab


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

5.1 Practices from Home


Constructors of a class can be both public and private. Explain why you would create a private constructor. Create a
Capital University of Science and Technology, Islamabad Page 47
Department of Computer Science (2017)
Lab 5 – Abstraction III

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.
6. Procedure & Tools
6.1 Tools
Visual Studio 2008.

6.2 Setting-up Visual Studio 2008 [Expected time = 5 mins]


Setup Visual Studio and make a project named “english”.

6.3 Walkthrough Task [Expected time = 30 mins]


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.

6.3.1 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
Capital University of Science and Technology, Islamabad Page 48
Department of Computer Science (2017)
Lab 5 – Abstraction III

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

6.3.2 Compilation
After writing the code, compile your code according to the guidelines mentioned. Remove any errors and warnings
that are present in your code.

6.3.3 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

7. Practice Tasks
This section will provide more practice exercises which you need to finish during the lab. You need to finish the
tasks in the required time. When you finish them, put these tasks in the following folder:
\\dataserver\assignments$\OOP\Lab05

7.1 Practice Task 1 [Expected time = 50 mins]


Street legal is an international motorbike developer stationed in Italy. The company has a reputation for producing
bikes that are extremely expensive, powerful and rare. Street legal has developed a brand new model called the
Grand Prix motorbike. The company produces a very limited number of Grand Prix each year. The company is
producing the Grand Prix in only one colour called the “Red”.
When the company has produced a Grand Prix, the Motorcycle has a number of attributes like colour, cubic
capacity, year of manufacture, engine number, frame number and owner name. Out of these attributes the attributes
that remain the same for all Grand Prix being produced are color, and cubic capacity.
Suppose you are working on a system specially designed for the Grand Prix. 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 motorbikes.
 Generate another object named “obj2” that is created by copying only those attributes that are the same from
“obj1”.

Capital University of Science and Technology, Islamabad Page 49


Department of Computer Science (2017)
Lab 5 – Abstraction III

 Initialize the remaining attributes with values of your own.

7.2 Practice Task 2 [Expected time = 15 mins]


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.

7.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.

7.4 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Colour = Red After selective copying only the permanent attributes contain
Owner = Ali Raza values.
Year of manufacture = 2013 Colour = Red
Cubic Capacity = 5700 Owner =
Engine number = 123456 Year of manufacture =
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.

Table 2: Confirmation of practice tasks T1 and T2

Practice Tasks Confirmation Comments


T1
T2

8. Evaluation Task (Unseen) [Expected time = 45 mins]


The lab instructor will assign you an unseen task depending upon the progress of the students.

9. Evaluation Criteria
The evaluation criteria for this lab will be based on the completion of the following tasks. Each task is assigned
marks which will be evaluated by the instructor in the lab depending on the accomplishment of the assigned tasks.

Capital University of Science and Technology, Islamabad Page 50


Department of Computer Science (2017)
Lab 5 – Abstraction III

Table 3: Evaluation of the Lab

Sr. Task No Description Marks


No.
1 4.1 Problem Modelling 10
2 6 Procedures and Tools 5
3 7.1 Practice task 1 with Testing 30
4 7.2 Practice task 2 with Testing 20
5 8 Evaluation Tasks (Unseen) 25
6 Good Programming 10
Practices
Total Marks 100

10. Further Reading

10.1 Books
 Object-Oriented Programming Using C++, Fourth edition, Joyce Farrell

10.2 Slides
The slides and reading material can be accessed from the folder of the class instructor available at
\\dataserver\jinnah$\

Capital University of Science and Technology, Islamabad Page 51


Department of Computer Science (2017)

Vous aimerez peut-être aussi