Encapsulation in C++

Unit 2 Β· Topic 2.1⏱ 10 min readπŸ“Š 1 diagram❓ 5 MCQs

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

Encapsulation diagram showing private data hidden inside a class with public methods as interface

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

  1. Define encapsulation.
  2. Difference between encapsulation and abstraction?
  3. Why are data members usually private?
  4. What is data hiding?

Long Questions

  1. Explain encapsulation with a C++ example.
  2. 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.