📘 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
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
Bark
सारांश
- virtual enables runtime polymorphism — the object's real type decides which method runs.
- Use a base-class pointer to a derived object.
💻 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ें.