0% found this document useful (0 votes)
2 views5 pages

Lecture - Virtual Function

Virtual functions are member functions in a base class intended to be overridden in derived classes, enabling runtime polymorphism. This concept is prevalent in C++ and allows the correct function to be selected based on the object's actual type. Key aspects include the use of the 'virtual' keyword, the importance of polymorphism, and the optional 'override' keyword for error checking.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views5 pages

Lecture - Virtual Function

Virtual functions are member functions in a base class intended to be overridden in derived classes, enabling runtime polymorphism. This concept is prevalent in C++ and allows the correct function to be selected based on the object's actual type. Key aspects include the use of the 'virtual' keyword, the importance of polymorphism, and the optional 'override' keyword for error checking.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Virtual functions

A virtual function is a member function in a base class that you expect to be overridden in
derived classes. It enables runtime polymorphism, which means the correct function is selected
at runtime based on the type of the object, not the type of the pointer or reference.

This concept is commonly used in C++ and other object-oriented programming languages.
#include <iostream>
using namespace std;

class Animal {
public:
virtual void speak() {
cout << "Animal speaks" << endl;
}
};

class Dog : public Animal {


public:
void speak() {
cout << "Dog barks" << endl;
}
};

int main() {
Animal* a = new Dog();
a->speak(); // Outputs: Dog barks
delete a;
}
Key Concepts:
virtual keyword: Declares a function as virtual in the base class.
Polymorphism: The correct function is chosen based on the object's actual type, not the
pointer type.
override keyword (optional but recommended): Helps catch errors by ensuring you're really
overriding a base class function.
When to Use Virtual Functions:
When you have a base class pointer or reference pointing to a derived class object.
When you want to ensure that the derived class's implementation is used.

You might also like