Lab 03 Class Scope and Accessing Class Members: 1. Objectives
Lab 03 Class Scope and Accessing Class Members: 1. Objectives
Members
February 27, 2024, 08:30 am to 11:30 am
Instructor: Dr. M. Umar Khan
Instructions:
1. Lab Reports must be submitted in both hard and soft forms before the deadline.
2. The cover page of the assignment must clearly state the Name and Registration of the
student along with the title of the Lab.
3. For online submission use MS Team group of section BCE 2B.
4. All lab reports are assessed as per rubric defined in the course description file (CDF).
1. Objectives
The objective of this lab is to teach the students, the scope of class data members and its member
functions.
2. Outcome
At the end of this lab student will be familiar with the accessing rules of class data
members and member functions
3. Introduction
In object oriented programming, methods and variables have various scope. Scope means that
the method or variable may or may not be directly accessible to other objects or classes. Classes
that do not have instances may be accessible to the system.
Page 1 of 4
3.2. Instance Scope
Instance variables and instance methods are associated with a specific object. They can
access class variables and methods.
3.6. Encapsulation
The process of providing a public interface to interact with the object while hiding other
information inside the object is called encapsulation.
4. Examples
The following program illustrates the usage of objects and classes in C++:
// The program uses public member functions to input two private numbers,
add two private numbers and display the result
#include<iostream>
using namespace
std;
private:
public:
Page 2 of 4
iNum2=iVar2;
}
void disp(void) //Member function
};
add A1;
cin>>iY;
A1.input(iX, iY);
A1.sum();
A1.disp();
system("pause");
5. Lab Tasks
5.1. Code the example given above and check the errors if you try to access the private
data members in main() function.
5.2. Modify the above task by making the scope of public member functions as private.
Create access functions in public scope to access private member functions from
main().
Page 3 of 4
5.3. Code the example given above and include a private constructor in the class. Create
objects of this class. Test the code and write down how the constructor will be called
or unable to be called?.
6. Home Tasks
6.1. Create a class of subtraction having two private data members. Create class methods
to get data from users and for subtraction of data members. Use appropriate access
modifiers for class methods.
7. References
[i] http://www.tutorialspoint.com/cplusplus/cpp_class_access_modifiers.htm
[ii] http://www.learncpp.com/cpp-tutorial/83-public-vs-private-access-specifiers/
Page 4 of 4