Object Oriented Programming Lab 5
Object Oriented Programming Lab 5
C++ Encapsulation
Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users. To
achieve this, you must declare class variables/attributes as private (cannot be accessed from
outside the class). If you want others to read or modify the value of a private member, you can
provide public get and set methods.
Sample Code:
#include <iostream>
using namespace std;
class Employee {
private:
// Private attribute
int salary;
public:
// Setter
void setSalary(int s) {
salary = s;
}
// Getter
int getSalary() {
return salary;
}
};
int main() {
Employee myObj;
myObj.setSalary(50000);
cout << myObj.getSalary();
return 0;
Output:
Example explained
Sample Code:
#include <bits/stdc++.h>
using namespace std;
class Geeks
{
// Access specifier
public:
// Data Members
string geekname;
// Member Functions()
void printname()
{
cout << "Geekname is: " << geekname;
}
};
int main() {
Syntax:
function_name(object_name);
Sample Code:
#include <iostream>
using namespace std;
class Student {
public:
double marks;
};
int main() {
Student student1, student2(56.0);
Student1.marks=88.0;
return 0;
}
Output:
Sample Code:
class Student {
public:
double marks1, marks2;
return student;
}
};
int main() {
Student student1;
// Call function
student1 =student1.createStudent();
return 0;
}
Output:
TASKS:
TASK 1:
Create a class named ‘Student’ that has the following private data members:
1. course1_gpa
2. course2_gpa
3. course3_gpa
And the following member functions:
1. Student (){}
2. Student (float cg1, float cg2, float cg3) {}
3. void calculateCGPA (Student s){}
Calculate & display the final CGPA for one Student using the above formula.
TASK 2:
Create a class named ‘Employee’ that has the following private data members:
1. salary
2. hours_worked
3. total_hours (N), N = 40 hours/week
4. salary_per_hour (N), N =1500
And the following member functions:
1. Employee (){}
2. Employee (float hw, float th, float sph) {}
3. Employee calculateSalary (){}