Data abstraction and encapsulation are two important concepts in object-oriented programming
(OOP). They allow programmers to create complex, modular programs that are easier to
understand and maintain.
Data abstraction is the process of hiding the implementation details of a data type or function and
only exposing the essential characteristics and behavior. It allows users to focus on the
functionality of the data type or function, rather than its internal implementation.
For example, consider a stack data structure. A stack is a last-in, first-out (LIFO) data structure
that allows users to push elements onto the stack and pop them off. The essential characteristics
of a stack are that it has a fixed size, can hold a certain type of data, and has specific push and
pop operations. The implementation details, such as how the stack is implemented using an array
or linked list, are hidden from the user.
Encapsulation is the process of bundling the data and functions that operate on that data within a
single unit, or object. It allows users to access the data and functions through a well-defined
interface, rather than directly accessing the internal representation of the data.
For example, consider a class that represents a bank account. The class might have private data
members for the account balance and account number, and public member functions for
depositing and withdrawing money. The internal representation of the account balance is hidden
from the user, who can only access it through the deposit and withdraw functions.
In C++, data abstraction and encapsulation can be achieved using classes and objects. A class is a
blueprint for an object, and an object is an instance of a class.
Here is an example of a simple stack class in C++:
C++ Code:
#include <iostream>
#define MAX_SIZE 100
, Abstraction and Encapsulation in C++
using namespace std;
class Stack {
private:
int arr[MAX_SIZE]; // array to store the stack
int top; // top of stack
public:
// Constructor
Stack() { top = -1; }
// Push an element onto the stack
void push(int x) {
if (top >= MAX_SIZE - 1) {
cout << "Error: stack overflow" << endl;
return;
}
arr[++top] = x;
}
// Pop an element off the stack
int pop() {
if (top < 0) {