0% found this document useful (0 votes)
8 views

LAB NO 4 OOPS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

LAB NO 4 OOPS

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

LAB NO.

5
18/10/2024

ENCAPSULATION USING GETTERS AND SETTERS

Lab outcomes:
After completing this lab, students will be able to;
 Understand concept of Encapsulation
 Basic Implementation of Getters and Setters.

Corresponding CLO and PLO:


 CLO-2, PLO-3 (Design and Development of solution)

Theory:
Encapsulation in C++

Encapsulation is one of the key pillars of Object-Oriented Programming (OOP)


in C++. It refers to the bundling of data and methods that manipulate the
data into a single unit called a class. It also involves restricting access to
certain components, ensuring that they are only accessible through
designated methods. This not only protects the integrity of the data but also
provides an abstraction layer between the internal workings of a class and its
usage.

1. What is Encapsulation?

 Encapsulation is the process of combining data (variables) and the


code (methods) that operate on that data into a single entity called a
class.
 It hides the internal representation of an object from the outside world
and allows access only through well-defined interfaces (methods).
 The main idea is to shield the data from direct access and
manipulation, ensuring that the data is accessed in a controlled
manner.

class Box {
public:
double getVolume(void) {
return length * breadth * height;
}
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};

2. How to Achieve Encapsulation in C++?

 Use Classes: Define a class that bundles the related data and
methods together.
 Access Specifiers: Use C++ access specifiers (public, private,
protected) to control the visibility of the class members (data members
and methods).
 Getters and Setters: Implement methods (also known as getter and
setter methods) to provide controlled access to private members.

3. Access Specifiers in C++

C++ provides three main access specifiers to control the accessibility of


class members:

Access Scope/Visibility
Specifier Usage
public Members are Used for methods and attributes that
accessible from should be accessed directly by other
outside the class. parts of the program.
private Members are Ensures that data cannot be accessed
accessible only within directly from outside the class,
the class itself. maintaining data integrity.
protected Members are Typically used in inheritance scenarios
accessible within the where derived classes need controlled
class and its derived access to base class members.
classes.

4. What Are Getters and Setters?


Get and set functions, also known as getters and setters, are public methods
used to access and modify private or protected data members of a class.
They are an essential part of encapsulation in object-oriented programming,
ensuring controlled access to the attributes of a class.

 Getters:
o These are methods that return the value of a private/protected
attribute.
o They provide read-only access, meaning that users of the class
can view the value without modifying it directly.
o Syntax: DataType getAttributeName();
 Setters:
o These are methods that set or update the value of a
private/protected attribute.
o They provide write or update access with validation logic if
needed to ensure the value being set is appropriate.
o Syntax: void setAttributeName(DataType value);
5. Why Use Getters and Setters?
 Data Encapsulation: By using getters and setters, the internal
representation of data is hidden from external access. This ensures
that the data cannot be modified directly, maintaining its integrity.
 Data Validation: Setters allow us to add validation logic before
modifying the value of an attribute. This prevents invalid data from
being set.
 Control Access: Getters and setters allow fine-grained control over
how and when the data can be accessed or modified.
6. Code Example: Getters and Setters

#include <iostream>
using namespace std;

class Car {
private:
int year;
public:

// Getter for year


int getYear() {
return year;
}

// Setter for year


void setYear(int y) {
if (y > 1885 && y <= 2024) { // Validating a reasonable year range
for cars
year = y;
} else {
cout << "Invalid year!" << endl;
}
}

// Method to display car information


void displayCarInfo() {
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
cout << "Price: $" << price << endl;
}
};
int main() {
Car myCar;

// Using setters to assign values to private attributes


myCar.setYear(2020);

// Display the car information using the display method


myCar.displayCarInfo();

return 0;
}

7. Explanation of the Code Example


1. Private Attributes: The Car class has three private attributes: model,
year, and price.
o These attributes cannot be accessed directly from outside the
class.
2. Public Getter Methods:
o getModel(), getYear(), and getPrice() provide read-only access to
the private attributes. They return the value of each attribute
without allowing modification.
3. Public Setter Methods:
o setModel(string m), setYear(int y), and setPrice(double p) allow
controlled modification of the attributes.
o Each setter method includes validation logic:
 setYear() ensures that the year is within a reasonable
range for a car.
 setPrice() ensures that the price is not negative.
o If invalid data is provided, the setter displays an error message
and does not update the attribute.
4. Controlled Access:
o By using setters, we ensure that the class remains in a valid
state and that only acceptable values are assigned to the
attributes.
8. Advantages of Using Getters and Setters
 Data Validation: As shown in the example, we can add checks in
setters to ensure that only valid data is assigned to attributes.
 Encapsulation: By making attributes private and using getters and
setters, we hide the internal representation, thus encapsulating the
class’s state.
 Flexibility: If we need to change how data is stored or retrieved (e.g.,
formatting or converting units), we only need to modify the getter or
setter without affecting the rest of the codebase.

Tasks:
Lab Task 1: write a program that has a class consisting of two
private members and two public member, that can explain
encapsulation using getter and setter function in OOP.
Code:
Output:

Lab Task 2: Write a program that has a class of 4 private data


members of student name, CMS, current semester and CGPA, take
values from user and assign to data members using setter and
getter method.
Code:
Output:

Observations:
In this lab we have done some tasks in which we used private and public
access specifiers and placed some variables in it and call those values in int
main and for private values to call we used getters and setters and with the
help of them we call all the values.
Rubrics
Report not Content that The The Appropri Conclusion
submitted has been requirement observati ate drawn
plagiarized s are ons, as measure correctly
or that has described,
well as ments or with exact
Laborato been as well as
submitted the the numeric results and
ry
incompletel experiment complete al a complete
Reports
y al process. technique analysis report in
, are are every way
document carried
ed. out.
Category Ungrade Very Poor Poor Fair Good Excellent
d
Marks 0 1 2 3 4 5

Date Total Instructor’s Signature


Marks

Demonst Absent The The student The The student The student
ration student understands student has created successfully
is unable the followed a functional developed a
to presented instructio or working functional
adequat laboratory ns to build schematic, model,
ely instructions the core model, logic, circuit,
follow and is schematic block block
the familiar with , block diagram, or diagram, or
instructi the lab diagram, code and code and
ons environment code, or has completed
provided but Cannot model. successfull the lab
. The setup With y run the objective in
student simulation some program or real-time or
can according to assistance circuit on a in a
name design but , the software simulation
the knows how student platform. environment
hardwar to perform can set up With , achieving
e or simulation and run minimum the expected
simulatio the assistance, results. They
n simulation they can can set up,
platform, . On the set up and operate, and
but protoboar run the run the
Cannot d/trainer/s simulation. simulation
setup or imulation on their own.
perform software
the
simulatio
n
Category Ungrad Very Poor Fair Good Excellent
ed Poor
Marks 0 1 2 3 4 5

Date Total Instructor’s


Marks Signature

You might also like