📘 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.

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

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.