📘 Lesson  ·  Lesson 71

Virtual Functions

What is a Virtual Function?

💡 Note

A virtual function lets the correct overridden method run based on the actual object type at runtime (runtime polymorphism).

Example

C++
#include <iostream>
using namespace std;
class Animal {
public:
    virtual void sound() { cout << "Some sound\n"; }
};
class Dog : public Animal {
public:
    void sound() override { cout << "Bark\n"; }
};
int main() {
    Animal* a = new Dog();
    a->sound();   // Bark (runtime decides)
    return 0;
}
Output:
Bark

Summary

  • virtual enables runtime polymorphism — the object's real type decides which method runs.
  • Use a base-class pointer to a derived object.

a Virtual Function क्या है?

💡 Note

A virtual function lets the correct overridden method run based on the actual object type at runtime (runtime polymorphism).

Example

C++
#include <iostream>
using namespace std;
class Animal {
public:
    virtual void sound() { cout << "Some sound\n"; }
};
class Dog : public Animal {
public:
    void sound() override { cout << "Bark\n"; }
};
int main() {
    Animal* a = new Dog();
    a->sound();   // Bark (runtime decides)
    return 0;
}
Output:
Bark

सारांश

  • virtual enables runtime polymorphism — the object's real type decides which method runs.
  • Use a base-class pointer to a derived object.
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.