Encapsulation in C++
Encapsulation is one of the object oriented programming concepts which binds the data and functions together. It makes the whole thing into a single unit.
Generally, this
single unit is considered as a class. Encapsulation is achieved by using access
specifiers as follows..
‘public’: member
variables can be accessible for anywhere in the class.
‘private’:
this type of variable accessed by current class only.
‘protected’:
it can be accessible by class and derived class.
Let us
create a c++ program to display the student details.
C++
program:
Here, ‘Student’
is the class. It has set() method to display the data. The get() method gets
the data.
Using the
object, we call the set() and get() function.
Code:
#include
<iostream>
using
namespace std;
class Student {
private:
string
s_name;
string
s_id;
int s_age;
public:
//
Constructor
Student(string
s_name,string s_id ,int s_age) {
this->s_name
= s_name;
this->s_id
= s_id;
this->s_age
= s_age;
}
// Setter for student name
void
setName(string s_name) {
this->s_name
= s_name;
}
// Getter for student name
string
getName() {
return
s_name;
}
// Setter
for student id
void
setId(string s_id) {
this->s_id
= s_id;
}
// Getter for student id
string
getId() {
return
s_id;
}
// Setter for age
void
setAge(int s_age) {
this->s_age
= s_age;
}
// Getter for age
int
getAge() {
return
s_age;
}
};
int main() {
// Creating
an objects of Student class
Student
stu("Ajay","S1",15);
Student
stu1("Jey","S2",14);
// using get functions
cout
<< "Name: " << stu.getName() << endl;
cout
<< "Id: " << stu.getId() << endl;
cout
<< "age: "<< stu.getAge()<<endl;
cout
<< "Name: " << stu1.getName() << endl;
cout
<< "Id: " << stu1.getId() << endl;
cout
<< "age: "<< stu1.getAge()<<endl;
//using set functions
stu.setName("kumar");
stu.setId("S3");
stu.setAge(16);
stu1.setName("James");
stu1.setId("S4");
stu1.setAge(20);
// Accessing modified data members using getter methods
cout
<< "Name: " << stu.getName() << endl;
cout
<< "Id:" <<stu.getId()<<endl;
cout
<< "Age: " << stu.getAge() << endl;
cout
<< "Name: " << stu1.getName() << endl;
cout
<< "Id:" <<stu1.getId()<<endl;
cout
<< "Age: " << stu1.getAge() << endl;
return 0;
}
Output:
Name: Ajay
Id: S1
age: 15
Name: Jey
Id: S2
age: 14
Name: kumar
Id:S3
Age: 16
Name: James
Id:S4
Age: 20
Thus, the
c++ program to illustrate encapsulation was explained successfully. Hope, you
liked the blog post. Keep coding!!!
Comments
Post a Comment