# 🔹 Abstract Class and Pure Virtual Function in C++ (Beginner-Friendly Guide)

## 📌 Introduction

In C++, sometimes we want to **define rules** but do not want to provide the **implementation** in the base class.  
In such cases, we use **Abstract Classes** and **Pure Virtual Functions**.

These concepts are a core part of **Object-Oriented Programming (OOP)**.

---

## 🔹 The Problem with a Normal Class

```plaintext
class Animal {
public:
    void sound() {
        cout << "Animal sound" << endl;
    }
};
```

### Why is this a problem?

Every animal has a different sound:

* Dog → Bark
    
* Cat → Meow
    
* Cow → Moo
    

The base class **cannot decide the exact behavior**.

---

## 🔹 Solution: Pure Virtual Function

### Definition:

A **Pure Virtual Function** is a virtual function that:

* Has **no implementation** in the base class
    
* **Must be implemented** by the derived (child) class
    

---

## 🔹 Syntax of a Pure Virtual Function

```plaintext
virtual void functionName() = 0;
```

`= 0` means:

> “This function has no body here.  
> Derived classes must implement it.”

---

## 🔹 Example of a Pure Virtual Function

```plaintext
class Animal {
public:
    virtual void sound() = 0;   // Pure virtual function
};
```

This means:

> Every animal must make a sound,  
> but **how** it sounds will be decided by the child class.

---

## 🔥 What Is an Abstract Class?

### Definition:

A class that contains **at least one pure virtual function** is called an **Abstract Class**.

### Important Rule:

```plaintext
Animal a;   // ❌ Error
```

❌ You **cannot create an object** of an abstract class.

---

## 🔹 Relationship Between Abstract Class and Pure Virtual Function

```plaintext
Pure Virtual Function
        ↓
Class becomes incomplete
        ↓
Class becomes ABSTRACT
        ↓
Object cannot be created
        ↓
Derived class must implement the function
```

---

## 🔹 Implementing the Pure Virtual Function (Child Class)

```plaintext
class Dog : public Animal {
public:
    void sound() {
        cout << "Dog barks" << endl;
    }
};
```

✔ Rule is followed  
✔ Class becomes complete (concrete class)

```plaintext
Dog d;
d.sound();   // Output: Dog barks
```

---

## 🔹 What If the Child Class Does NOT Implement It?

```plaintext
class Cat : public Animal {
    // sound() not implemented
};
```

❌ Error  
👉 `Cat` also becomes an **abstract class**

---

## 🔹 Example Using Polymorphism

```plaintext
int main() {
    Animal* a;
    Dog d;

    a = &d;
    a->sound();   // Calls Dog's sound()
}
```

### Output:

```plaintext
Dog barks
```

✔ This is **runtime polymorphism**

---

## 🔹 Abstract Class vs Normal Class

| Feature | Normal Class | Abstract Class |
| --- | --- | --- |
| Object creation | Allowed | ❌ Not allowed |
| Function body | Always present | May be missing |
| Pure virtual function | ❌ No | ✅ Yes |
| Purpose | Implementation | Rule / blueprint |
