📘 Lesson  ·  Lesson 71

Virtual Functions

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.

Virtual Function क्या है?

💡 Note

Virtual function runtime पर actual object type के आधार पर सही overridden method चलाता है (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 तय करता है)
    return 0;
}
Output:
Bark

सारांश

  • virtual runtime polymorphism देता है — object का असली type तय करता है कौन सा method चले।
  • Derived object को base-class pointer से use करें।
← Back to C++ Tutorial
🔗

Share this topic with a friend

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

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

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

\n