Encapsulation in C++
Introduction
Encapsulation is the bundling of data (variables) and the functions that operate on that data into a single unit called a class. It also hides the internal state from the outside world, exposing only a controlled public interface.
This is often called data hiding: the data members are made private, and access is provided through public getter/setter methods.
Diagram
Fig 2.1 β Encapsulation wraps data + functions; data is private, accessed via public methods.
Definition
Encapsulation: The wrapping up of data and functions into a single unit (class), with data hidden from direct external access.
C++ Code Example
#include <iostream>
using namespace std;
class Student {
private:
int roll;
string name;
public:
void set(int r, string n) { roll = r; name = n; }
void get() { cout << roll << " " << name << endl; }
};
int main() {
Student s;
s.set(101, "Ravi");
s.get();
// s.roll = 5; // error: private
return 0;
}
Advantages
- Data protection and integrity.
- Controlled access via methods.
- Easier maintenance and modification.
- Improved modularity.
Important Questions
Short Questions
- Define encapsulation.
- Difference between encapsulation and abstraction?
- Why are data members usually private?
- What is data hiding?
Long Questions
- Explain encapsulation with a C++ example.
- Discuss advantages of encapsulation in software design.
MCQ Practice
1. Encapsulation is achieved by:
- Inheritance
- Access specifiers (private/public)
- Templates
- Virtual functions
Answer: access specifiers.
2. Private members are accessible:
- Only within the class
- From anywhere
- From derived classes only
- From main() only
Answer: only within the class.
3. Getter/setter methods are usually:
- private
- public
- protected
- static
Answer: public.
4. Which of these is NOT a benefit of encapsulation?
- Data hiding
- Modularity
- Multiple inheritance
- Maintainability
Answer: multiple inheritance.
5. By default, members of a class are:
- private
- public
- protected
- static
Answer: private.
Quick Revision
- Encapsulation = data + methods in one class.
- Data hidden via private; access via public methods.
- Default member access is private.
- Improves security and maintainability.