Nothing Special   »   [go: up one dir, main page]

Access Specifiers, Constructors and Destructors

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

Lab Manual for Object Oriented Programming

(LAB-03)
Access Specifiers, Constructors and Destructors

University of Management and Technology Page 1


Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

Table of Contents
1. Introduction 24

2. Activity Time boxing 24

3. Objective of the Experiment 24

4. Concept Map 25
4.1 Access Specifiers – Public and Private Access 25
4.2 Constructors 25
4.3 Destructors 26

5. Home Work Before Lab 27


5.1 Practices from home 27

6. Procedure & Tools 27


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

7. Practice Tasks 29
7.1 Practice Task 1 29
7.2 Outcomes 30
7.3 Testing 30

8. Evaluation Task (Unseen) 30

9. Evaluation Criteria 31

10. Further Reading 31


10.1 Books 31
10.2 Slides 31

Page 2
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

Lab 03: Access Specifiers, Constructors and


Destructors
1. Introduction
Programming that you studied in the previous semester does not strongly support programming practices like
encapsulation and data hiding. In fact these features are almost nonexistent in sequential programming. Object
Oriented Programming is purely based on these practices and enforces these practices through various techniques. In
this regard access specifiers play a very important role because they are the first line of defence in secure
programming.
This lab is designed to teach three very basic yet essential concepts of OOP namely access specifiers, constructor and
destructors. Access specifiers provide a technique through which we can restrict access to data members and member
functions. After enforcing access it is important to reduce our reliance on too many member functions. Constructors
offer a very attractive and easy to implement technique through which we can take steps call procedures whenever
an object is created. The use of constructors is preferred over the use of member functions because constructors are
called automatically and hence they can invoke further functions whereas simple member functions have to be called
sequentially one by one every time an object is created.
Similarly this lab also focuses on the use of destructors that are called whenever an object goes out of scope. In this
the lab the students will be familiarized with the use of access specifiers, constructors and destructors.

Relevant Lecture Material

 Lectures: 3, 4, 5, 6
 Textbook: Object-Oriented Programming Using C++, Fourth edition, Robert Lafore
o Pages: 201-212

2. Activity Time boxing


Table 1: Activity Time Boxing
Task No. Activity Name Activity time Total Time
5.1 Evaluation of Design 20 mins 20 mins
6.2 Setting-up Visual Studio 5 mins 5 mins
6.3 Walkthrough Tasks 40 mins 40 mins
7 Practice tasks 60 mins 60 mins
8 Evaluation Task 55 mins 55 mins
Total Time 180 Minutes

3. Objective of the Experiment


After completing this lab the student should be able to:
 Clearly understand the purpose and importance of access specifiers.
 Develop a class by correctly using/ enforcing access specifiers.
 Differentiate between the public and private access specifier.
 Understand the importance of constructors.
 Understand the importance of destructors.
 Use a basic constructor.
 Use a basic destructor.

Page 3
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

4. Concept Map

4.1 Access Specifiers – Public and Private Access

Access specifier also known as access modifier provides a technique for enforcing access control to class members
(data members and member functions). The use of access specifiers enforces encapsulation and data hiding. C++
provides three access specifiers i.e. public, private and protected. In this lab we will only cover the public and the
private access specifier. The protected specifier is left for future discussions.

The public access specifier is the one that provides unrestricted access to the class members. While the private access
specifier provides a very strict/ restricted access to class members. All the class members that are written under the
public access can be accessed both inside and outside the class without any restriction. On the other hand all the class
members written as private are accessible inside the class but are not accessible outside the class. The best and most
common way of accessing private data members is through the use of a public functions.

When we are discussing access specifiers it must be pointed out that by default classes are private whereas structures
are public. Hence if you do not write private then your listed class members are considered private in a class.

The correct convention for the use of access specifiers is that data members are kept private whereas functions are
kept public. Hence you are providing a public interface for accessing restricted items in a class.

using namespace std;


class myclass

private:
int datamember; //Private data member
public:
int memberfun(int); // public member function
};

int myclass :: memberfun (int x) // This function is still public because its prototype is public

datamember=x;

void main( )

myclass obj;
//Syntax Error: private member
obj.memberfun(10);

4.2 Constructors
A constructor is a function that is automatically called when an object is created. This function can exhibit the regular
behaviour of any function. The reason why constructors are needed is that unlike regular functions which need to
deliberately called, a constructor will be automatically called when an object is created. Every constructor has a body
from where we can call regular member functions.
A very important question which is often asked is that how does the compiler know that the constructor function

Page 4
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

needs to be called automatically? The answer is very simple. A constructor is a function that has the same name as the
class. Whenever an object is created the compiler searches for a function having the same name as the class i.e. the
constructor. Given below is a sample code that shows the class constructor. Generally the constructor is defined as
public. Also the constructor can be overloaded like a regular member function. An important point regarding a
constructor is that it cannot return a value. In fact writing the keyword void is strictly prohibited.

using namespace std;


class myclass

private:
int datamember; //Private data member
public:
myclass( ); //Class constructor

cout<<”Hello you have called the class constructor”;

};

void main( )

myclass obj;

4.3 Destructors
Constructors are designed to help initialize/ create an object. Destructors on the other hand do exactly the opposite.
Destructors are called whenever an object goes out of scope. When this happens it is necessary to perform cleanup
procedures especially when you have used dynamic memory or you have been working with pointers in your code.
The destructor function can be used to free up memory that you have allocated or dereference pointers that were
referenced. The rules for a destructor are as follows:
 They have the same name as the class just simply preceded by a tilde (~)
 They can take no arguments
 They cannot return anything, not even void.

using namespace std;


class myclass

private:
int datamember; //Private data member
public:
myclass( ); //Class constructor

cout<<”Hello you have called the class constructor”;

~myclass( ); //Class constructor

cout<<”Hello you have called the class destructor”;

};

Page 5
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

5. Home Work Before Lab

5.1 Practices from home


Your task is to carefully understand the code provided. Analyze the code and suggest any corrections that may be
needed. There are both syntax and logical errors in the code so consider both when designing the correct solution.
Submit the correct code to the lab instructor.

class student
{
int age;
int cnic;
int semester;
char name;
public:
int setall(int a, int c, int s, int sem, char n) const;
{
age=a;
c=cnic;
semester=s;
name=n;
}
}

int myclass :: displayall ( )


{
cout<<”The entered data is”<<student.data;
}

void main( )
{
Student obj;
obj::setall( );
obj.displayall( );
obj.setage( );
Student anotherobj;
Student::anotherobj::setall( );
}

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 “pizza”.

6.3 Walkthrough Task [Expected time = 40 mins]


Write a program that creates a class called pizza. The data members of the class are size, toppings, price, thickness,
extra toppings. Through the use of a constructor initialize the class object. Determine what is public and private in the
class.

Page 6
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

6.3.1 Writing Code


In the source file created in the project “pizza” write the following C++ code:

class pizza
{
private:
int size, price, thickness;
string topping;
public:
void setsize()
{
cout<<"Enter size of pizza: ";
cin>>size;
}
void setprice()
{
cout<<"Enter price of pizza: ";
cin>>price;
}
void setthickness()
{
cout<<"Enter thickness of pizza: ";
cin>>thickness;
}
void settopping()
{
cout<<"Enter toppings of pizza: ";
cin>>topping;
}
void display() const
{
cout<<"The ordered pizza details are: ";
cout<<"\nSize: "<<size;
cout<<"\nPrice: "<<price;
cout<<"\nTopping:"<<topping;
cout<<"\nThickness:"<<thickness<<"\n";
}
pizza() //class constructor: cannot have a return type
{
setsize();
setprice();
setthickness();
settopping();
}
};
void main()
{
pizza obj;
obj.display( );
}
Figure 1: The pizza class demonstrating the use of a constructor

Page 7
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

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

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\Lab03

7.1 Practice Task 1 [Expected time = 60 mins]


Write a C++ program that creates a program for a new ice cream vendor called LeCream. The management of
LeCream has decided that they are going to sell their ice cream in 7 different flavours namely chocolate, vanilla,
strawberry, mango, tutti fruit, almond crunch and coffee. Carefully design the program by observing the following
rules.
 LeCream is charging Rs 100 for two scoops and Rs 150 for three scopes. Hence you will need a function to
determine the number of scoops and based on that the price. If a user enters more than three scoops your
program should display invalid input and it should exit.

 LeCream allows its customers to purchase a vanilla wafer with their ice cream. If the customer wants to
purchase the wafer he will have to pay an additional Rs 10. This amount should be added to the total amount
payable by the user.

 If the customer asks for chocolate flavour then he will have to pay an additional amount i.e. Rs 120 for two
scoops and Rs 180 for three scopes. Design a function that will be called if the customer chooses flavoured
ice cream.

 The program should show a menu that asks the customer for his requirements and then displays the final
payable amount with full details about the flavour, number of scoops and wafer
Page 8
University of Management and Technology
Department of Computer Science, SST
Access Specifiers, Constructors and Destructors

 In the end create a class destructor that displays a thank you message to the user.

Design your program using sound OOP practices. Carefully determine the data members, member functions, access
specifiers, activities to be performed in the constructor. Make sure that you use good naming conventions in your
code. A good design can earn you higher marks.

7.2 Outcomes
After completing this lab, students will be able to design a class that correctly implements class members by observing
access specifiers. The students will also be familiar with the use of a constructor and destructor.

7.3 Testing
Test Cases for Practice Task-1
Sample Inputs Sample Outputs
Flavour = chocolate Your choice of ice cream is as follows
Wafer required = yes Flavour = chocolate
Number of scoops = 3 Number of scoops = 3
Wafer is required
Total price is 190

Thank you for visiting LeCream!

Flavour = Almond crunch Your choice of ice cream is as follows


Wafer required = No Flavour = Almond Crunch
Number of scoops = 2 Number of scoops = 2
Wafer is not required
Total price is 100

Thank you for visiting LeCream!

Flavour = Coffee Your choice of ice cream is as follows


Wafer required = yes Flavour = Coffee
Number of scoops = 3 Number of scoops = 3
Wafer is Required
Total price is 160

Thank you for visiting LeCream!

Flavour = Mango Invalid Input


Wafer required = No
Number of scoops = 4 Thank you for visiting LeCream!

Table 2: Confirmation of practice tasks T1

Practice Tasks Confirmation


T1

8. Evaluation Task (Unseen) [Expected time = 55 Mins]


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

Page 9
University of Management and Technology
Department of Computer Science, SST
Exception Handling

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.

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 50
4 8.1 Evaluation Tasks (Unseen) 15
5 Good Programming 10
Practices
Total Marks 90

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$\

Page 32
University of Management and Technology
Department of Computer Science, SST

You might also like