0% found this document useful (0 votes)
25 views19 pages

Lab 03

The copy constructor gets called twice in the given function. When the function is called and the object is passed by value, the copy constructor is called to copy the object being passed to the parameter. Then when the function returns the object, the copy constructor is called again to copy the returned object to the calling function. So in summary, the copy constructor gets called twice - once for the parameter and once for the return value. Task 02: Shallow Copy [Estimated 10 minutes / 10 marks] Given the following class: class Test { public: int *ptr; Test(int x) { ptr = new int; *ptr = x; } };

Uploaded by

aimenzahid600
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)
25 views19 pages

Lab 03

The copy constructor gets called twice in the given function. When the function is called and the object is passed by value, the copy constructor is called to copy the object being passed to the parameter. Then when the function returns the object, the copy constructor is called again to copy the returned object to the calling function. So in summary, the copy constructor gets called twice - once for the parameter and once for the return value. Task 02: Shallow Copy [Estimated 10 minutes / 10 marks] Given the following class: class Test { public: int *ptr; Test(int x) { ptr = new int; *ptr = x; } };

Uploaded by

aimenzahid600
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/ 19

CC-211L

Object Oriented Programming

Laboratory 03

Classes Objects and Member Functions - II

Version: 1.0.0

Release Date: 26-01-2023

Department of Information Technology


University of the Punjab
Lahore, Pakistan
CC-211L Object Oriented Programming FALL 2022

Contents:
• Learning Objectives
• Required Resources
• General Instructions
• Background and Overview
o Reference to an Object
o Copy Constructors
o Const Keyword
o Composition
o Member Initializer List
• Activities
o Pre-Lab Activity
▪ Default memberwise assignment
▪ Copy Constructor
▪ Example Code 1
▪ When do we need to define our own copy constructor?
▪ Example Code 2
▪ Example Code 3
▪ Exercise 1
▪ Task 01: Copy Constructor text
▪ Task 02: Shallow Copy
▪ Task 03: Deep Copy
o In-Lab Activity
▪ Creating Reference to an Object
▪ Example Code 4
▪ Using Reference to an Object
▪ Returning Reference to a private data member
▪ Importance of const keyword in returning reference to a private data member
▪ Example Code 5
▪ Example Code 5 after using const keyword
▪ Task 01: Access using Reference as return type
▪ Task 02: Update an array using reference as return type
▪ Task 03: Forbid Change
o Post-Lab Activity
▪ Task 01: Composition with two classes
▪ Task 02: Composition with three classes
• Submissions
• Evaluations Metric
• References and Additional Material
• Lab Time and Activity Simulation Log

Laboratory 03 – Classes Objects and Member Functions - II Page 2 of 19


CC-211L Object Oriented Programming FALL 2022

Learning Objectives:
• Returning Reference to private Data Members
• Default Memberwise Assignment
• const Objects
• const Member Functions
• Object Composition and Aggregation
• Class Separation using header

Resources Required:
• Desktop Computer or Laptop
• Microsoft ® Visual Studio 2022

General Instructions:
• In this Lab, you are NOT allowed to discuss your solution with your colleagues, even not
allowed to ask how is s/he doing, this may result in negative marking. You can ONLY discuss
with your Teaching Assistants (TAs) or Lab Instructor.
• Your TAs will be available in the Lab for your help. Alternatively, you can send your queries
via email to one of the followings.

Teachers:
Course Instructor Prof. Dr. Syed Waqar ul Qounain [email protected]

Saad Rahman [email protected]


Teacher Assistants
Zain Ali Shan [email protected]

Laboratory 03 – Classes Objects and Member Functions - II Page 3 of 19


CC-211L Object Oriented Programming FALL 2022

Background and Overview:


Reference to an Object:
A reference to an object in C++ is an alias that allows you to access an object by another name. It is
similar to a pointer, except that you do not need to use the dereference operator (*) to access the object.
A reference is created using the & operator. References are typically used to create a more concise and
efficient way of referring to an object without needing to copy the object itself. Additionally, references
can be used to pass an object into a function without needing to make a copy of the object.
Copy Constructors:
A copy constructor in C++ is a special constructor for a class that is used to create a new object as a
copy of an existing object. It is usually used when an object is passed by value into a function or returned
from a function. It typically takes a single argument of the same type as the class being constructed and
creates a new object as a copy of the argument object.
Const Keyword
The const keyword in C++ is used to declare a constant. It is a modifier that indicates that the value of
the variable or object it is applied to cannot be changed. Constants are useful for declaring values that
will not change throughout the program, such as mathematical constants or other unchanging values.
Composition
Composition in C++ is a way to combine objects or classes into a bigger class or object. This type of
relationship is known as a "has-a" relationship, as the composed class "has a" reference to the other
class. Composition is used to model a "part-of" relationship, where one object can contain multiple
smaller objects. This allows for complex behavior with simpler parts. For example, a car class may
contain a steering wheel, an engine, and a transmission as separate objects. All of these objects work
together to make up the car, but can be managed and updated independently. The composition also
allows for greater flexibility and reuse of code, as the objects can be changed and reused in different
contexts.
Member Initializer List:
Member Initializer Lists in C++ are a way to initialize data members of a class. They are used to
initialize member variables to a known state before the body of the constructor is run.

Laboratory 03 – Classes Objects and Member Functions - II Page 4 of 19


CC-211L Object Oriented Programming FALL 2022

Activities:
Pre-Lab Activities:
Default memberwise assignment (Default copy constructor):
Default memberwise assignment is a feature of the C++ programming language that enables implicit
copies of data members when an object is assigned to another. In other words, when an object is
assigned to another, the data members of the first object are copied to the second object. This is done
automatically by the compiler unless the user specifies that the assignment operator should be
overridden. This is a shallow copy, meaning that any pointers or references are simply copied, not
their values.
Copy Constructor:
A copy constructor is a special constructor in C++ that creates an object by initializing it with an
existing object of the same type. The copy constructor will make a deep copy, meaning that any
pointers or references will be copied with their values. The copy constructor is used to create a new
object with updated values from an existing object.
Example Code 1:
Default member-wise assignment and copy constructors are generally similar in their usage when
used in a static environment like shown in the code below. Their syntax is also generally the same,
with the copy constructor sometimes being initialized as object1(object2) instead of object1=object2.

Fig. 01 (Default member-wise assignment and copy constructors)


When do we need to define our own copy constructor?
The Copy constructor and the assignment operators are used to initializing one object to another object.
The main difference between them is that the copy constructor creates a separate memory block for the
new object. But the assignment operator does not make new memory space. It uses the reference
variable to point to the previous memory block. If we don’t define our own copy constructor, the C++
compiler creates a default copy constructor i.e. default member-wise assignment operator, for each class

Laboratory 03 – Classes Objects and Member Functions - II Page 5 of 19


CC-211L Object Oriented Programming FALL 2022

which does a member-wise copy between objects. The compiler created copy constructor works fine in
general. We need to define our own copy constructor only if an object has pointers or any runtime
allocation of the resource like file handle, a network connection, etc.
Example Code 2:
Following example shows shallow copy i.e., default assignment operator usage:

Fig. 02 (Shallow Copy Constructor)

Laboratory 03 – Classes Objects and Member Functions - II Page 6 of 19


CC-211L Object Oriented Programming FALL 2022

Output:

Fig. 03 (Output Shallow Copy Constructor)


Example Code 3:
Only a user-defined copy constructor is added in the above code in this example. This example shows
that this type of copy constructor handles all the pointers and references related to original object in the
new made copied object unlike assignment operator.

Fig. 04 (Deep Copy Constructor)


Output:

Fig. 05 (Output Deep Copy Constructor)


Exercise 1:

Laboratory 03 – Classes Objects and Member Functions - II Page 7 of 19


CC-211L Object Oriented Programming FALL 2022

Fig. 06 (Exercise 1)
Write expected output of above code:

Output >

Laboratory 03 – Classes Objects and Member Functions - II Page 8 of 19


CC-211L Object Oriented Programming FALL 2022

Task 01: Copy Constructor [Estimated 05 minutes / 05 marks]


How many times copy constructor gets called for the following function:
Given Code:

Fig. 07 (Pre-Lab Task)


Write expected output of above code:

Output >

Submit “.txt” file named “Task1” on Google Classroom.


Task 02: Shallow Copy [Estimated 20 minutes / 20 marks]
Write a C++ program to create a distance class with feet and inches as data members. Use default
memberwise assignment operator to produce expected output.
Expected Output:

Fig. 08 (Pre-Lab Task)


Submit “.c” file named “Task2” on Google Classroom.

Task 03: Deep Copy [Estimated 25 minutes / 25 marks]


Write a C++ program to create a Container class with a constructor, destructor and a parameterized
constructor to implement deep copy when copying data from one object to another. The Container class
should have a set_dimension() function to set the dimensions and a show_data() function to display the
dimensions of the Container. One of the three dimensions should use a pointer to dimension.

Laboratory 03 – Classes Objects and Member Functions - II Page 9 of 19


CC-211L Object Oriented Programming FALL 2022

Expected Output:

Fig. 09 (Pre-Lab Task)


Submit “.c” file named “Task 3” on Google Classroom.

Laboratory 03 – Classes Objects and Member Functions - II Page 10 of 19


CC-211L Object Oriented Programming FALL 2022

In-Lab Activities:
Creating Reference to an Object:
1. Instantiate an object: To create a reference to an object in C++, first, you must instantiate an object.
This can be done with a simple declaration, like "MyObject myObject;"
2. Create a reference variable: To create a reference variable, use the syntax "Type &name = object;"
For example, "MyObject &myObjectRef = myObject;"
3. Use the reference variable: Now you can use the reference variable to access the properties and
functions of the object it is referencing. For example, "myObjectRef.doSomething();"
Example Code 4:

Fig. 10 (Creating Reference to an Object Code)


Output:

Fig. 11 (Output Creating Reference to an Object Code)


Using Reference to an Object:
Let us examine the following example, which further illustrates the use of referencing an object.

Fig. 12 (Using Reference to an Object Code)

Laboratory 03 – Classes Objects and Member Functions - II Page 11 of 19


CC-211L Object Oriented Programming FALL 2022

Output:

Fig. 13 (Output Using Reference to an Object Code)


Returning Reference to a private data member:
Returning a reference to a private data member is a way for a class to allow other classes and functions
to access a private variable without making the variable public. This allows the private variable to
remain protected while still providing a way for it to be accessed.
Importance of const keyword in returning reference to a private data member:
The use of the const keyword is of utmost importance in this regard, as it prevents external code from
modifying private data members by not allowing the reference to be used to change their values. If the
reference return type is declared const, the reference is a nonmodifiable lvalue, meaning it cannot be
used to modify the data. On the other hand, if the reference return type is not declared const, it can lead
to subtle errors.
Example Code 5:
Here is an example where the const keyword is not used as the return type of a reference, which can
result in the modification of private data members of a class and thus undermine the purpose of
encapsulation.

Laboratory 03 – Classes Objects and Member Functions - II Page 12 of 19


CC-211L Object Oriented Programming FALL 2022

Fig. 14 (Example Code of Importance of const keyword)


Output:

Fig. 15 (Output Example Code of Importance of const keyword)

Laboratory 03 – Classes Objects and Member Functions - II Page 13 of 19


CC-211L Object Oriented Programming FALL 2022

Example Code 5 after using const keyword:


If we use the `const` keyword as a return type, the compiler will prevent any modification of private
data members of a class, thus preserving the concept of encapsulation while still allowing access to
those members. As seen in the code snippet below, the compiler will throw an error on any lines where
we attempt to change the values of private data members.

Fig. 16 (Example Code of Importance of const keyword)


Output:

Fig. 17 (Output Example Code of Importance of const keyword)

Laboratory 03 – Classes Objects and Member Functions - II Page 14 of 19


CC-211L Object Oriented Programming FALL 2022

Task 01: Access using Reference as return type [40 minutes / 20 marks]
Write a C++ program to create a class Set5 with an array of 5 integers and the following functions:
setElements(), copy constructor, and an overloaded operator ++. Allow the user to enter values of a
Set5 object and create a copy with each element incremented by one. Display the values and addresses
of the elements in main() using a display function with reference as return type.
Sample Output:

Fig. 18 (In-Lab Task 01)


Submit “.c” file named “Task1” on Google Classroom.
Task 02: Update an array using reference as return type. [40 minutes / 30 marks]
Write a program that will allow the user to create an array of a specified size, enter a number and a
position within the array, and then update the array accordingly. An output of the updated array will be
displayed. The program will utilize a function with a reference return type in order to update the array
with the user's inputs.
Do not allocate extra space for another array. You must do this by modifying the input array in-place.
Sample Output:

Fig. 19 (In-Lab Task 02)

Laboratory 03 – Classes Objects and Member Functions - II Page 15 of 19


CC-211L Object Oriented Programming FALL 2022

Submit “.c” file named “Task2” on Google Classroom.


Task 03: Forbid Change [10 minutes / 10 marks]
Update this code so that the user won’t be able to change the dog’s breed once entered.

Fig. 20 (In-Lab Task 03)


Submit “.c” file named your “Task3” on Google Classroom.

Laboratory 03 – Classes Objects and Member Functions - II Page 16 of 19


CC-211L Object Oriented Programming FALL 2022

Post-Lab Activities:
Task 01: Composition with two classes [Estimated 20 minutes / 10 marks]
Design a Line class to be implemented using composition with the Point class. The program should
allow users to create Lines using two Points, and output the coordinates of each Point. Create
constructors and getter/setter methods for each class, and write the logic in main () to generate the
Lines and display the coordinates of the two Points.

Fig. 21 (Post-Lab Task 01)


Submit “.c” file named your “Task1” on Google Classroom.

Task 02: Composition with three classes [Estimated 40 minutes / 20 marks]


Write a program that uses composition to define classes, Time, Date and Event, which are used to store
and print the details related to an event. The program should allow the user to enter the details of the
event, such as the hour, day, month, year and name of the event. There should be a function named
printEventData() in the event class. In main(), when this function is called with an argument like the
name of the event or date of the event, all the details entered by the user for that event should be printed
on screen. For example, if the user enters the date 25/12/2020, and there are two objects with this date,
the output should be:
Christmas occurs on 25/12/2020 at 06:00
Quaid’s Birthday occurs on 25/12/2020 at 01:15
And make sure to display when constructors and destructors are called for each class.
Note: Objects are constructed from the inside out (contained classes will be constructed first) and
destructed in the reverse order, from the outside in (container class will be destructed first).
Submit “.c” file named your “Task2” on Google Classroom.

Laboratory 03 – Classes Objects and Member Functions - II Page 17 of 19


CC-211L Object Oriented Programming FALL 2022

Submissions:
• For In-Lab Activity:
▪ Save the files on your PC.
▪ TA’s will evaluate the tasks offline.
• For Pre-Lab & Post-Lab Activity:
▪ Submit the .c file on Google Classroom and name it to your roll no.

Evaluations Metric:
• All the lab tasks will be evaluated offline by TA’s
• Division of Pre-Lab marks: [50 marks]
▪ Task 01: Copy Constructor [05 marks]
▪ Task 02: Shallow Copy [20 marks]
▪ Task 03: Deep Copy [25 marks]
• Division of In-Lab marks: [60 marks]
▪ Task 01: Access using Reference as return type [20 marks]
▪ Task 02: Update an array using reference as return type [30 marks]
▪ Task 03: Forbid Change [10 marks]
• Division of Post-Lab marks: [30 marks]
▪ Task 01: Composition with two classes [10 marks]
▪ Task 02: Composition with three classes [20 marks]

References and Additional Material:


• Copy Constructors
https://www.tutorialspoint.com/difference-between-copy-constructor-and-assignment-
operator-in-cplusplus

• Return By Reference
https://www.scaler.com/topics/cpp-return-reference/

• Const object and data members


https://www.linuxtopia.org/online_books/programming_books/thinking_in_c++/Chapter08_0
24.html

• Composition
https://www.geeksforgeeks.org/object-composition-delegation-in-c-with-examples/

Laboratory 03 – Classes Objects and Member Functions - II Page 18 of 19


CC-211L Object Oriented Programming FALL 2022

Lab Time Activity Simulation Log:


• Slot – 01 – 00:00 – 00:15: Class Settlement
• Slot – 02 – 00:15 – 00:30: In-Lab Task
• Slot – 03 – 00:30 – 00:45: In-Lab Task
• Slot – 04 – 00:45 – 01:00: In-Lab Task
• Slot – 05 – 01:00 – 01:15: In-Lab Task
• Slot – 06 – 01:15 – 01:30: In-Lab Task
• Slot – 07 – 01:30 – 01:45: In-Lab Task
• Slot – 08 – 01:45 – 02:00: In-Lab Task
• Slot – 09 – 02:00 – 02:15: In-Lab Task
• Slot – 10 – 02:15 – 02:30: In-Lab Task
• Slot – 11 – 02:30 – 02:45: Evaluation of Lab Tasks
• Slot – 12 – 02:45 – 03:00: Discussion on Post-Lab Task

Laboratory 03 – Classes Objects and Member Functions - II Page 19 of 19

You might also like