Lesson 14 +30 XP

Encapsulation, Information Hiding, ADTs & Object Identity

Encapsulation, Information Hiding, ADTs & Object Identity

A class is more than a structure with functions. It is a way to protect data and to separate what a type does from how it does it. This lesson covers encapsulation and information hiding through access specifiers, abstract data types, and the three properties every object has: identity, state and behaviour.

1. Encapsulation

Encapsulation is the bundling of data and the functions that operate on it into a single unit, the class. The data and functions belong together and are used together.

Information hiding (data hiding) is the principle that a class should hide its internal details, especially its data, and expose only what users need. In C++ encapsulation provides the unit, and the access specifiers provide the hiding.

SpecifierAccessible from member functionsfrom friendsfrom derived classesfrom outside (objects)
private✅✅❌❌
protected✅✅✅❌
public✅✅✅✅

The usual design is private data with public member functions. The public functions are the only way to read or change the data, so the class can check every change.

Why hide information?

  1. Validity: the class can reject bad values (no negative age, no withdrawal above the balance).
  2. Freedom to change: the internal representation can be changed without affecting users, as long as the public interface stays the same.
  3. Simpler use: users see a small, clear interface, not the internal details.
  4. Fewer bugs: data can be changed only in a few known places, so errors are easy to trace.
C++
#include <iostream>
using namespace std;

class Student {
    int roll;
    float marks; // hidden: must stay between 0 and 100
public:
    void setRoll(int r) {
        roll = r;
    }
    void setMarks(float m) {
        if (m >= 0 && m <= 100) {
            marks = m;
        } else {
            cout << "Rejected marks " << m << endl;
            marks = 0;
        }
    }
    float getMarks() {
        return marks;
    }
    char grade() {
        if (marks >= 75) {
            return 'A';
        }
        if (marks >= 60) {
            return 'B';
        }
        if (marks >= 40) {
            return 'C';
        }
        return 'F';
    }
    void show() {
        cout << "Roll " << roll << ": " << marks << " (" << grade() << ")" << endl;
    }
};

int main() {
    Student s1, s2;
    s1.setRoll(1);
    s1.setMarks(82);
    s2.setRoll(2);
    s2.setMarks(135); // the class refuses an invalid value
    s1.show();
    s2.show();
    // s2.marks = 135;                // error: marks is private
    return 0;
}

Output:

OUTPUT
Rejected marks 135
Roll 1: 82 (A)
Roll 2: 0 (F)

Functions like getMarks are called accessors (getters); functions like setMarks are mutators (setters).

2. Abstract Data Types (ADT)

An abstract data type is a type defined by the operations it supports and their behaviour, not by how it is stored. A user of an ADT knows what each operation does, not how.

A class is the C++ way to implement an ADT:

  • the public member functions are the operations (the interface);
  • the private data members and the function bodies are the implementation, hidden from the user.

Because classes use data abstraction, they are called abstract data types, and objects of a class are instances of the ADT.

Example: a Stack ADT

The user calls push, pop, isEmpty. Whether the stack is stored in an array or a linked list is hidden; the implementation below uses an array, and it could be changed without touching main.

C++
#include <iostream>
using namespace std;

class Stack {
    enum {
        SIZE = 5
    };
    int data[SIZE]; // hidden representation
    int top;

public:
    void init() {
        top = -1;
    }
    bool isEmpty() {
        return top == -1;
    }
    bool isFull() {
        return top == SIZE - 1;
    }
    void push(int x) {
        if (isFull()) {
            cout << "Overflow: cannot push " << x << endl;
        } else {
            data[++top] = x;
        }
    }
    int pop() {
        if (isEmpty()) {
            cout << "Underflow" << endl;
            return -1;
        }
        return data[top--];
    }
};

int main() {
    Stack s;
    s.init();
    for (int i = 1; i <= 6; i++) {
        s.push(i * 10); // the sixth push overflows
    }
    cout << "Popped:";
    while (!s.isEmpty()) {
        cout << " " << s.pop();
    }
    cout << endl;
    s.pop();
    return 0;
}

Output:

OUTPUT
Overflow: cannot push 60
Popped: 50 40 30 20 10
Underflow
Part of the ADTIn the Stack class
Valuessequences of int with last-in-first-out order
Operations (interface)init, push, pop, isEmpty, isFull (public)
Implementation (hidden)the array data, the index top, and the function bodies (private)

3. Objects and Classes: Identity, State and Behaviour

Grady Booch describes every object by three properties.

PropertyMeaningIn C++
Statethe current values of the object's attributes; it may change over timethe values of the data members
Behaviourhow the object acts and reacts: the operations it can perform and how its state changesthe member functions
Identitythe property that distinguishes the object from all other objects, even ones with the same stateits own memory location (its address, this)

Two objects can have equal state but different identity: two Student objects with the same roll and marks are still two separate objects. Changing one does not change the other.

C++
#include <iostream>
using namespace std;

class Point {
    int x, y;

public:
    void set(int a, int b) {
        x = a;
        y = b;
    } // behaviour that changes state
    void move(int dx, int dy) {
        x = x + dx;
        y = y + dy;
    }
    bool sameState(Point& p) {
        return x == p.x && y == p.y;
    }
    void show() {
        cout << "(" << x << ", " << y << ")";
    }
};

int main() {
    Point p, q;
    p.set(2, 3);
    q.set(2, 3);
    Point& r = p; // r is another name for p: same identity

    cout << "p == q in state?    " << p.sameState(q) << endl; // equal state
    cout << "p, q same identity? " << (&p == &q) << endl;     // different objects
    cout << "p, r same identity? " << (&p == &r) << endl;     // the same object

    p.move(1, 1); // changes p's state (and so r's)
    cout << "p = ";
    p.show();
    cout << ", q = ";
    q.show();
    cout << ", r = ";
    r.show();
    cout << endl;
    return 0;
}

Output:

OUTPUT
p == q in state?    1
p, q same identity? 0
p, r same identity? 1
p = (3, 4), q = (2, 3), r = (3, 4)

The life of an object

An object is created (memory is allocated and a constructor runs), is used (messages change and report its state), and is destroyed (a destructor runs and memory is released). Lessons 16 and 17 cover constructors and destructors.

4. Encapsulation vs Abstraction vs Information Hiding

ConceptQuestion it answersAchieved by
AbstractionWhat should the user see?designing a simple public interface (and abstract classes)
EncapsulationWhat belongs together?putting data and functions in one class
Information hidingWhat should the user not touch?private and protected members

These work together: abstraction decides the interface, encapsulation groups the members, and information hiding protects everything behind the interface.

💡 Tip

Key points to remember

  • Encapsulation = data + functions in one unit; information hiding = keeping the data private behind public functions.
  • private: class and friends only. protected: also derived classes. public: everyone.
  • A class implements an ADT: public functions are the operations, private members the hidden implementation.
  • Every object has state (data values), behaviour (member functions) and identity (its own address).
  • Equal state does not mean the same object.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. Explain encapsulation and information hiding. How does C++ achieve them? (5 Marks)
  • Write: the definitions, the access specifier table, the four reasons, and the Student program.
  • Q2. What is an abstract data type? Explain with a Stack class. (5 Marks)
  • Write: the definition, the Stack program with output, and the ADT table.
  • Q3. Explain the identity, state and behaviour of an object with an example. (5 Marks)
  • Write: the three-row table and the Point program comparing p, q and r.
  • Q4. Differentiate between abstraction, encapsulation and information hiding. (2.5 Marks)