In C++, OOP encapsulation refers to the grouping of data and related functions inside a single class. In other words, encapsulation is defined as the Binding (or wrapping) code and data together into a single unit.
It restricts direct access to data and allows controlled modification through methods. It also helps to accomplish data hiding. It helps to preserve data, provides for regulated updates, and enhances security. It also helps to make code easier to maintain and understand.
Real-Life Example of Encapsulation
Consider a real-life example of the smartphone. We use the smartphone to make calls, snap photos, and open programs with a single touch. However, we cannot see what's inside: the circuits, cables, or how the system interprets each touch. Signal management, memory consumption, and security are all done behind the scenes.
In this regard, the smartphone functions similarly to a programming class. It stores both data (including battery life, messages, and contacts) and functions (including calling, texting, and browsing) in one place. As a user, we can simply interact with the screen (the public interface), while the inner workings are hidden. It is encapsulation, which provides helpful features while keeping internal mechanics protected and private.
Syntax of Encapsulation
It has the following syntax:
class Class_name {
private:
// Private data members
string string_name;
int int_digit;
public:
// Public setter method to set value
void setData(Type value);
// Public getter method to get value
Type getData();
};
In this syntax,
- Private: It represents the private variables that are not accessible directly from outside the class.
- Public: It represents the public variable and provides safe access to data.
- setData: It helps to modify private data securely.
- getData: It helps to access private data securely.
C++ Encapsulation Example
Let us take an example to demonstrate the encapsulation in C++.
Example
#include <iostream>
using namespace std; //using standard namespace
class Student //class name
{
private: //private data members
string name;
int roll_no;
float grade;
public:
Student(string stu_name, int r, float initial_grade)
{
name = stu_name;
roll_no = r;
ChangeGrade(initial_grade);
}
void ChangeName(const string& new_name) //using public method to change the name
{
name = new_name;
}
string nameGet() const //using getter method to get the students name
{
return name;
}
void ChangeRollNo(int new_roll)
{
roll_no = new_roll;
}
int rollNoGet() const //using getter method to retrieve the roll number
{
return roll_no;
}
void ChangeGrade(float new_grade)
{
if (new_grade >= 0.0f && new_grade <= 100.0f)
grade = new_grade;
else
cerr << "Error: Grade must be between 0 and 100.\n";
}
float gradeGet() const
{
return grade;
}
};
int main() //main function
{
Student s("Joseph", 1, 97.5f);
cout << "The name of the student is: " << s.nameGet() << endl;
cout << "The roll number is: " << s.rollNoGet() << endl;
cout << "The grade is: " << s.gradeGet() << "%" << endl;
s.ChangeName("John");
s.ChangeGrade(94.3f);
cout << "\nUpdated Student Details:\n";
cout << "The name of the student is: " << s.nameGet() << endl;
cout << "The roll number is: " << s.rollNoGet() << endl;
cout << "The grade is: " << s.gradeGet() << "%" << endl;
return 0;
}
Output:
The name of the student is: Joseph
The roll number is: 1
The grade is: 97.5%
Updated Student Details:
The name of the student is: John
The roll number is: 1
The grade is: 94.3%
Explanation:
In this example, we have taken a Student class by keeping data members (name, roll_no, and grade) private and accessing them using the public methods. After that, we use a constructor that initializes these members, while setter methods like ChangeName and ChangeGrade method enable controlled updates. Finally, the getter methods such as nameGet and gradeGet provide the safe read-only access.
Types of Encapsulation
In C++ , encapsulation is divided mainly into three categories. These type are as follows:
1) Member Variable Encapsulation
In C++, all data members are declared as private and can be accessed or modified using public getter and setter methods. It helps to keep data safe from direct external access.
2) Function Encapsulation
In C++, some functions are kept private, whereas others functions are public. It helps to reduce the number of processes that are exposed to the outside.
3) Class Encapsulation
The nested classes are made private within another classes. It enables us to limit access to internal classes from the outside code.
Role of Access Specifiers in Encapsulation
In C++, access specifiers are complex to implement encapsulation. They specify how and where class members (such as data and functions) can be accessible from different sections of the program. C++ has three main access specifiers:
1) Public Access Specifier
In C++, the data members declared as public can be accessible from anywhere in the program. It means that any functions or classes can directly access or modify these members both inside and outside of the class.
2) Private Access Specifier
When a member is declared private, it is only accessible to members of the same class. Any external access will result in a compilation error. It ensures that important information remains hidden and protected.
3) Protected Access Specifier
In C++, the protected access specifier is mainly utilized to specify that a class member can be accessed within the class itself and by its derived classes. It means that any function or object cannot access the protected members of the class outside the class. The protected members of a class are typically used to represent the implementation of a class that must be accessible to its derived classes.
C++ Encapsulation Example using Access Specifier
Let us take an example to demonstrate the encapsulation using Access Specifier in C++.
Example
#include <iostream>
using namespace std; // using standard namespace
class Bank_account { //using class
private: //private modifier
string acc_holder;
double acc_balance;
public: //public modifier
// Using Setter method
void setAccHolder(string name) {
acc_holder = name;
}
void deposit(double amount) {
if (amount > 0)
acc_balance += amount;
}
// Using Getter method for account holder name
string getAccHolder() const {
return acc_holder;
}
// Using Getter method for account balance
double getBalance() const {
return acc_balance;
}
};
int main() { //main function
Bank_account acc;
acc.setAccHolder("John");
acc.deposit(1670.80);
cout << "Account Holder: " << acc.getAccHolder() << endl;
cout << "Balance: $" << acc.getBalance() << endl;
return 0;
}
Output:
Account Holder: John
Balance: $1670.8
Explanation:
In this example, we demonstrate the encapsulation using a Bank_account class, where we use private data members as the account holder's name and balance. The access members are controlled using public setter and getter methods. After that, the setAccHolder method sets the name, deposit adds money to the balance, and getter functions provide read-only access.
Why Encapsulation in C++?
In C++, encapsulation is a fundamental concept in object-oriented programming (OOP) that needs to combine data and the methods that operate on it into a single class. It helps to secure the internal state of an object from unintentional or unwanted tampering by restricting direct access to its data.
Encapsulation imposes access via controlled methods, which are often known as getters and setters. These public methods control how internal data is read and updated, which ensures that only valid operations are performed.
Encapsulation is Important for Several Reasons
- It ensures that objects retain ownership over their data, which prevents unwanted changes from other parts of the program.
- It allows cleaner code by allowing class users to rely on the behavior of a function without having to understand how it works internally.
- Debugging and testing are made easier because data flow is constrained and limited to specified access points.
- It improves the program's security, maintainability, and flexibility by enabling internal implementation to evolve without affecting external code.
Features of Encapsulation
There are several features of Encapsulation in C++. Some main features are as follows:
- Hidden Data: It maintains internal class data privacy to prevent unauthorized access and modification. It allows only specific functions that can access or modify the data.
- Abstraction: It allows us to see only the necessary details, while complex internal logic is hidden. It streamlines operations and avoids confusion for the end user.
- Access Control: Access control manages data accessibility through access specifiers. It helps to regulate what is displayed and what is kept hidden in the class.
- Modularity: It allows us to create class modules where both classes are independent and reusable. Every class can be creating and tested independently for improved maintainability.
- Controlled Interaction: It ensures that data is only modified safely using several ways. It prevents any accidently or unwanted modifications to the object's state.
Advantages of Encapsulation
There are several advantages of Encapsulation in C++. Some main advantages of encapsulation are as follows:
- In C++, encapsulation secures sensitive data by declaring class members because of private and limiting access to certain functionalities. It helps to avoid direct external tampering and maintains data integrity.
- It helps to prevent unauthorized program part from changing internal data. It is especially important in vital sectors, including banking, healthcare, and finance, where data security is essential.
- Encapsulated classes work as independent building blocks. It helps to improve code clarity and organization while also simplifying cooperation.
- Modifications can be done without affecting external code that depends on the class because internal details are hidden.
Disadvantages of Encapsulation
There are several disadvantages of Encapsulation in C++. Some main disadvantages of encapsulation are as follows:
- In C++, encapsulation can lead to increased code length because of the requirement for many getter and setter functions.
- In C+, private members cannot be accessed directly.
Conclusion
In conclusion, encapsulation is essential to creating secure, organized, and maintainable applications. It protects the internal state of objects by combining data and related functions into a single class and limiting direct access via controlled interfaces. It does not only ensure data integrity and security but also encourages modularity, code reuse, and cleaner software architecture, which makes it a main principle in effective object-oriented programming.
C++ Encapsulation MCQs
1) What does mean by encapsulation in C++?
- Implementing data hiding
- Only inheritance is used
- Functions can be overloaded
- Writing in-line functions
2) What access specifier is used in encapsulation to restrict access to class members in C++?
- public
- protected
- private
- global
3) How can we implement encapsulation in C++?
- Define all variables globally.
- Make variables public
- By writing multiple main functions
- By Combining data and functions in a class
4) Why is encapsulation so necessary in C++ OOP?
- Increases memory utilization.
- Improves security and modularity
- Slows program performance
- Increases code complexity.
5) Which of the following options represents the best advantages of encapsulation in C++?
- Global data access
- Direct object access
- Isolated modifications and secure data
- All members are publicly exposed