Skip to main content

Featured

Solve LeetCode 3 Longest Substring Without Repeating Characters in C++ using the sliding window

Longest Substring Without Repeating Characters in C++ LeetCode 3 · sliding window · last index array Table of Contents Problem Statement Approach 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 Conclusion Problem Statement 3. Longest Substring Without Repeating Characters Given a string s , find the length of the longest substring that contains no repeating characters. A substring is a continuous part of the string, so "pwke" is a subsequence of "pwwkew" but not a substring. Approach We use a sliding window . The window is the part of the string between start and end , and we always keep it free of repeated characters. An array lastIndex of size 128 remembers the most recent position of every ASCII ...

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

๐ŸŒ™