Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

C++ Abstract Class and Pure Virtual Function Example

C++ Abstract Class and Pure Virtual Function Example

✅ C++ Program: Abstract Class and Pure Virtual Functions

#include <iostream>
using namespace std;

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

// Derived class Dog
class Dog : public Animal {
public:
    void sound() override {
        cout << "Dog barks ๐Ÿถ\n";
    }
};

// Derived class Cat
class Cat : public Animal {
public:
    void sound() override {
        cout << "Cat meows ๐Ÿฑ\n";
    }
};

int main() {
    // Animal a;   ❌ ERROR: object of abstract class not allowed

    Animal *ptr;   // ✅ Abstract class pointer

    Dog d;
    Cat c;

    ptr = &d;
    ptr->sound();   // Calls Dog’s version

    ptr = &c;
    ptr->sound();   // Calls Cat’s version
}
  

๐Ÿ“˜ Explanation:

This program demonstrates the use of abstract classes and pure virtual functions in C++. Key points:

  • Animal is an abstract class because it has a pure virtual function sound().
  • You cannot create objects of abstract classes.
  • You can create pointers of abstract class type and point them to derived objects.
  • Runtime polymorphism ensures the correct function is called based on the object assigned.

๐Ÿงพ Sample Output:

Dog barks ๐Ÿถ
Cat meows ๐Ÿฑ
  

๐Ÿ”‘ Keywords:

C++ abstract class, pure virtual function, runtime polymorphism, OOPs in C++, C++ class hierarchy

๐Ÿ“Œ Hashtags:

#CPlusPlus #AbstractClass #Polymorphism #OOP #CppInterview #VirtualFunctions

๐Ÿ” Search Description:

This C++ program demonstrates abstract classes and pure virtual functions using Animal, Dog, and Cat classes. Explains runtime polymorphism with sample output.

Comments

Popular Posts

๐ŸŒ™