In C++, object-oriented programming (OOP) encapsulation involves bundling data and associated functions within a unified class. In simpler terms, encapsulation is described as the act of combining code and information into a cohesive entity.
It limits direct entry to data and permits managed alterations via methods. It also aids in achieving data concealment. This technique safeguards data, enables controlled revisions, and boosts security measures. Additionally, it simplifies the maintenance and comprehension of code.
Real-Life Example of Encapsulation
Consider a practical scenario involving a smartphone. A smartphone is utilized for various tasks such as making calls, capturing photographs, and launching applications effortlessly. Nonetheless, the internal components like circuits, cables, and the intricate process of interpreting touch commands remain hidden from the user. Functions like signal handling, memory usage, and ensuring device security are all carried out in the background, invisible to the user.
In this context, the smartphone operates much like a programming class. It holds various pieces of information (such as battery status, messages, and contact details) and functionalities (like making calls, sending messages, and browsing the internet) within a single entity. Users can easily engage with the display (the external interface), while the underlying operations remain concealed. This concept is encapsulation, offering convenient functionalities while safeguarding the internal workings.
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's consider an illustration to showcase 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 illustration, we've implemented a Student class where the attributes (name, roll_no, and grade) are encapsulated as private members, and their values are accessed through public member functions. Subsequently, a constructor is employed to set initial values, and setter functions like ChangeName and ChangeGrade are utilized for controlled modifications. Lastly, getter functions such as nameGet and gradeGet are used for secure retrieval of data.
Types of Encapsulation
In C++, encapsulation is primarily classified into three main categories. These categories are as follows:
1) Member Variable Encapsulation
In C++, every data member is defined as private and can be retrieved or updated through public getter and setter functions. This approach aids in safeguarding data from unauthorized external manipulation.
2) Function Encapsulation
In C++, certain functions are designated as private, while others are declared as public. This practice aids in minimizing the amount of operations that are accessible from external sources.
3) Class Encapsulation
The enclosed classes are designated as private within other classes, allowing us to restrict external code from accessing internal classes.
Role of Access Specifiers in Encapsulation
In C++, implementing encapsulation can be intricate due to access specifiers. These specifiers determine the accessibility of class members (like data and functions) from various parts of the program. C++ features three primary access specifiers:
1) Public Access Specifier
In C++, data members that are defined as public can be accessed from any part of the program. This allows functions or classes to easily interact with and alter these members, whether they are within or outside the class.
2) Private Access Specifier
When a member is marked as private, it can only be accessed by other members within the same class. Attempting to access it externally will lead to a compilation error. This concept guarantees the confidentiality and security of critical data.
3) Protected Access Specifier
In C++, the protected access specifier is primarily used to indicate that a class member can be accessed within the class and by its subclasses. This restricts access to the protected members from functions or objects outside the class. Protected members are commonly employed to encapsulate the class's implementation details that need to be available to its derived classes.
C++ Encapsulation Example using Access Specifier
Let's consider a scenario to showcase encapsulation through Access Specifiers in the C++ programming language.
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 instance, we showcase the concept of encapsulation through the implementation of a BankAccount class. Here, private data attributes such as the account holder's name and balance are utilized. The manipulation of these attributes is managed through public setter and getter functions. Subsequently, the setAccHolder function is responsible for assigning the name, deposit function increases the balance, and getter functions offer restricted read access.
Why Encapsulation in C++?
In C++, encapsulation represents a key principle in object-oriented programming (OOP) where data and its corresponding methods are consolidated within a singular class. This consolidation aids in safeguarding the inner state of an object against inadvertent or undesirable manipulation by limiting direct entry to its data.
Encapsulation enforces access through controlled methods, commonly referred to as getters and setters. These exposed methods regulate the reading and modification of internal data, guaranteeing the execution of only legitimate operations.
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 a number of drawbacks associated with Encapsulation in C++. Some key disadvantages of encapsulation include:
- Encapsulation in C++ may result in longer code due to the need for numerous getter and setter functions.
- In C++, direct access to private members is not permitted.
Conclusion
In summary, encapsulation plays a crucial role in developing secure, structured, and sustainable applications. By bundling data and relevant operations within a single class and restricting direct access through controlled interfaces, encapsulation safeguards the inner state of objects. This practice not only upholds data security and consistency but also fosters modularity, code reusability, and improved software design, establishing it as a fundamental tenet in proficient 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
By merging data and functions within 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