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

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.

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

\n

💻 Live Code Editor

Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें. Agar load na ho to naye tab mein kholें.