In “The C++ Programming Language by Bjarne Stroustrup”, a class is described as a user-defined data
type that represents a blueprint for creating objects (instances). A class encapsulates data (attributes)
and functions (methods) that operate on the data, promoting the principles of abstraction and
encapsulation.
Real-World Example:
Consider a Bank Account as a class:
- Attributes (Data Members): Account Number, Balance, Account Holder Name.
- Methods (Member Functions): Deposit, Withdraw, Check Balance.
Each customer’s bank account (an object) will have its own values for these attributes but will use the
same set of methods to interact with the account.
Graphical Representation of a Class:
In C++, a class can be represented graphically using UML (Unified Modeling Language) diagrams. A
simple class diagram is structured as a rectangle divided into three sections:
+---------------------------+
| BankAccount | <-- Class Name
+---------------------------+
| accountNumber: int | <-- Attributes (Data Members)
| balance: double |
| accountHolderName: string |
+---------------------------+
| deposit() : void | <-- Methods (Member Functions)
| withdraw() : void |
| checkBalance() : double |
+---------------------------+
```
In this diagram:
- The top section contains the class name (`BankAccount`).
- The middle section lists the data members (like `accountNumber` and `balance`).
- The bottom section lists the member functions (like `deposit () ` and `withdraw () `).
Key Points:
1. Encapsulation: Classes bundle both data and the methods that operate on that data, ensuring data
integrity.
2. Abstraction: Classes hide the internal details and only expose necessary functionalities through their
public interfaces.
This allows developers to create reusable, modular code and manage complexity in large programs.