Complete OOP Concepts in CPP
Complete OOP Concepts in CPP
Object-Oriented Programming (OOP) is based on four key principles that define how objects and
classes interact with each other. These principles are:
- **Encapsulation**: This principle involves bundling data (variables) and methods (functions) that
operate on that data into a single unit, a class. It also prevents direct access to some data,
restricting it through access specifiers like `private`, `public`, and `protected`.
**Example:**
```cpp
class Employee {
private:
int salary;
public:
void setSalary(int s) { salary = s; }
int getSalary() { return salary; }
};
```
- **Abstraction**: This principle hides the complex implementation details from the user and exposes
only the necessary functionalities. It helps in reducing complexity.
- **Inheritance**: This principle allows a new class (derived class) to acquire properties and behavior
from an existing class (base class). It promotes code reuse and hierarchical classification.
- **Polymorphism**: This principle allows the same function to behave differently in different
contexts, achieved through function overloading and method overriding.
A **class** is a user-defined data type that serves as a blueprint for creating objects, whereas an
**object** is an instance of a class.
**Example Code:**
```cpp
class Car {
public:
string brand;
void showBrand() { cout << "Brand: " << brand << endl; }
};
int main() {
Car myCar; // Object
myCar.brand = "Toyota";
myCar.showBrand();
}
```
3. Encapsulation in C++
Encapsulation is implemented in C++ using **access specifiers** such as `private`, `public`, and
`protected`. It prevents unintended modifications to data and enhances security.
**Example Code:**
```cpp
class Account {
private:
double balance;
public:
void setBalance(double b) { balance = b; }
double getBalance() { return balance; }
};
```
4. Constructor vs Destructor
**Example Code:**
```cpp
class Demo {
public:
Demo() { cout << "Constructor Called\n"; } // Constructor
~Demo() { cout << "Destructor Called\n"; } // Destructor
};
int main() {
Demo obj; // Constructor is called here
} // Destructor is called automatically when obj goes out of scope
```
**Example Code:**
```cpp
class Test {
private:
int x; // Only accessible within class
public:
int y; // Accessible everywhere
protected:
int z; // Accessible in derived class
};
```