Detailed Explanation of OOP Concepts in C++
1. Four Pillars of Object-Oriented Programming (OOP)
Object-Oriented Programming (OOP) is based on four main principles:
- **Encapsulation**: This refers to bundling data (variables) and methods (functions) that operate on
the data into a single unit called a class. It also restricts direct access to some data, preventing
unintended modifications.
Example:
```cpp
class Employee {
private:
int salary;
public:
void setSalary(int s) { salary = s; }
int getSalary() { return salary; }
};
```
- **Abstraction**: Hides implementation details and exposes only essential functionalities.
- **Inheritance**: Allows a new class (derived class) to inherit properties and behavior from an
existing class (base class), promoting code reuse.
- **Polymorphism**: Allows the same function to behave differently in different contexts, such as
function overloading and method overriding.
2. Difference Between a Class and an Object
A class is a blueprint for creating objects, while an object is an instance of a class.
**Example:**
```cpp
class Car {
public:
string brand;
void showBrand() { cout << "Brand: " << brand << endl; }
};
int main() {
Car myCar;
myCar.brand = "Toyota";
myCar.showBrand();
}
```
3. Encapsulation in C++
Encapsulation is the concept of restricting direct access to class members. This is implemented
using access specifiers: `private`, `public`, and `protected`.
**Example:**
```cpp
class Account {
private:
double balance;
public:
void setBalance(double b) { balance = b; }
double getBalance() { return balance; }
};
```
4. Constructor vs Destructor
A **constructor** is a special method that initializes an object when it is created. A **destructor** is
used to clean up resources when an object is destroyed.
**Example:**
```cpp
class Demo {
public:
Demo() { cout << "Constructor Called"; }
~Demo() { cout << "Destructor Called"; }
};
int main() {
Demo obj;
}
```
5. Purpose of Access Specifiers
Access specifiers define the scope and accessibility of class members.
- `private`: Accessible only within the class.
- `public`: Accessible from outside the class.
- `protected`: Accessible within the class and derived classes.
**Example:**
```cpp
class Test {
private:
int x;
public:
int y;
protected:
int z;
};
```
6. Data Hiding in OOP
Data hiding is a technique to restrict direct access to class members and allow controlled access
through public methods. This improves security and maintainability.
**Example:**
```cpp
class BankAccount {
private:
double balance;
public:
void deposit(double amount) { balance += amount; }
double getBalance() { return balance; }
};
```