Thanks to visit codestin.com
Credit goes to www.scribd.com

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

Virtual Functions

Virtual functions are a key feature in object-oriented programming that enable runtime polymorphism, allowing derived classes to override base class methods. They facilitate dynamic method dispatch, where the method executed is determined by the actual object type rather than the reference type. While they offer advantages like extensibility and code reusability, virtual functions also introduce performance and memory overhead.

Uploaded by

kagrawal2201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views5 pages

Virtual Functions

Virtual functions are a key feature in object-oriented programming that enable runtime polymorphism, allowing derived classes to override base class methods. They facilitate dynamic method dispatch, where the method executed is determined by the actual object type rather than the reference type. While they offer advantages like extensibility and code reusability, virtual functions also introduce performance and memory overhead.

Uploaded by

kagrawal2201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 5

Virtual Functions in Object-Oriented Programming (OOP)

A virtual function is a function in a base class that you expect to be overridden in derived classes. It allows for
runtime polymorphism, meaning that the function called is determined at runtime based on the object type, not
the reference type.

In simpler terms, a virtual function enables dynamic method dispatch, where the method that's executed is
based on the type of the object that the base class reference or pointer is pointing to, rather than the type of the
reference or pointer itself.

Virtual functions are fundamental in implementing polymorphism in object-oriented programming (OOP).


They allow a program to behave differently based on the actual object type, even when using base class
references or pointers.

Key Concepts of Virtual Functions

1. Dynamic Binding: When you use a base class reference or pointer to call a virtual function, the call is
resolved at runtime, depending on the type of the object being pointed to, rather than the type of the
reference or pointer.
2. Overriding: A derived class provides a specific implementation of the function, which replaces the base
class implementation when called through a base class pointer or reference.
3. Virtual Table (vtable): Behind the scenes, the mechanism for resolving virtual function calls is
typically implemented using a virtual table (vtable), which is an array of pointers to virtual functions.
Each class that has virtual functions has its own vtable.
4. Base Class and Derived Class Interaction: Virtual functions are used when we expect that a derived
class will provide a specific implementation, but we want to handle the object using a reference or
pointer to the base class.

Syntax
In C++

To declare a function as virtual, the virtual keyword is used in the base class, usually in the function
definition.

Example in C++:

#include <iostream>
using namespace std;

class Animal {
public:
// Declare this function as virtual
virtual void sound() {
cout << "Animal makes a sound" << endl;
}
};

class Dog : public Animal {


public:
// Override the virtual function
void sound() override {
cout << "Dog barks" << endl;
}
};

class Cat : public Animal {


public:
// Override the virtual function
void sound() override {
cout << "Cat meows" << endl;
}
};

int main() {
Animal* animal; // Pointer to base class

Dog dog;
Cat cat;

animal = &dog;
animal->sound(); // Outputs: Dog barks

animal = &cat;
animal->sound(); // Outputs: Cat meows

return 0;
}

How It Works:

1. The sound() method in the base class Animal is declared as virtual.


2. Both Dog and Cat classes override this method.
3. In the main() function, the animal pointer, which is of type Animal*, points to an object of the Dog
class and later to the Cat class.
4. Despite using a base class pointer (animal), the appropriate method (Dog::sound() or Cat::sound())
is called at runtime, demonstrating runtime polymorphism.
Virtual Function Mechanism

 Base Class Reference/Pointer: In the example above, the base class pointer Animal* animal can point
to objects of derived classes (Dog and Cat).
 Runtime Decision: The actual method (sound()) that's invoked is determined at runtime, based on the
object the pointer is pointing to (e.g., Dog or Cat), not on the type of the pointer (Animal*).

Why Use Virtual Functions?

1. Polymorphism: Virtual functions allow for polymorphic behavior. They are essential for enabling one
function to behave differently depending on the actual object type, even when you're interacting with the
object through a base class reference or pointer.
2. Extensibility: Virtual functions allow for easy extension of the code. You can add new derived classes
without modifying the existing code that uses base class references/pointers. This is a key advantage in
designing flexible and maintainable systems.
3. Flexible Code: You can write more generic code that works with base class pointers or references but
still handles different derived types appropriately by overriding virtual functions.

Key Points About Virtual Functions

 Dynamic Binding: The mechanism where the function to be called is determined at runtime is called
dynamic or late binding. This is the opposite of static binding (which is the default in non-virtual
functions).
 virtual keyword: A function must be marked with the virtual keyword in the base class to enable
runtime polymorphism.
 override keyword: In C++11 and later, the override keyword is used to explicitly mark a method that
overrides a base class method. While it’s not required, it helps ensure that you’re correctly overriding a
base class method and prevents accidental method signatures from causing issues.
 Virtual Destructor: If a class has virtual functions, its destructor should also be virtual to ensure proper
cleanup of derived objects when they are deleted via a base class pointer.

Example in C++ (Virtual Destructor):

class Animal {
public:
virtual ~Animal() { // Virtual destructor
cout << "Animal destroyed" << endl;
}
};

class Dog : public Animal {


public:
~Dog() override {
cout << "Dog destroyed" << endl;
}
};

int main() {
Animal* animal = new Dog(); // Base class pointer
delete animal; // Proper destruction, calling Dog's destructor
return 0;
}

Output:
Dog destroyed
Animal destroyed

In this case, the virtual destructor ensures that when an object is deleted via a base class pointer
(Animal*), the destructor of the derived class (Dog) is called first, followed by the base class destructor
(Animal).

Virtual Function Table (vtable)

 When a class contains virtual functions, the compiler typically sets up a vtable for the class. The vtable
is a table of function pointers, one for each virtual function in the class.
 Each object of the class contains a pointer to the vtable. This pointer allows the program to call the
correct function when a virtual function is invoked on an object.
 The vtable allows for dynamic dispatch at runtime, ensuring the correct method is called based on the
actual object type.

Example in C++ (Explaining vtable Concept):


class Shape {
public:
virtual void draw() { // Virtual function
cout << "Drawing a shape" << endl;
}
};

class Circle : public Shape {


public:
void draw() override { // Override the virtual function
cout << "Drawing a circle" << endl;
}
};

int main() {
Shape* shape = new Circle();
shape->draw(); // Outputs: Drawing a circle

delete shape;
return 0;
}

 In this example, at runtime, the program will use the vtable to dispatch the call to the correct version of
draw() (either Shape::draw() or Circle::draw()).
 The vtable ensures that the correct function is called, even though the base class pointer Shape* is used.

Advantages of Virtual Functions

1. Polymorphism: Virtual functions enable runtime polymorphism, allowing the same function to behave
differently based on the type of the object.
2. Extensibility and Flexibility: You can extend functionality by adding new derived classes without
changing existing code.
3. Code Reusability: Virtual functions allow code in the base class to be reused while still providing
specialized behavior in derived classes.
4. Simplifies Code: Virtual functions allow complex systems to be represented with simple interfaces.

Disadvantages of Virtual Functions


1. Performance Overhead: The dynamic binding mechanism (vtable) introduces some overhead. The
program must look up the correct function in the vtable, which takes slightly more time than calling a
non-virtual function.
2. Memory Overhead: Each object of a class with virtual functions requires additional memory to store
the pointer to the vtable.
3. Can Cause Errors if Misused: Improper overriding or misunderstanding of how virtual functions work
can lead to unexpected behavior or bugs, especially if virtual destructors are not used in base classes.

Conclusion

Virtual functions are an essential feature of object-oriented programming that enable runtime polymorphism.
They allow for flexible and extensible systems where the behavior of methods can differ based on the actual
object type at runtime, even when using base class pointers or references. Virtual functions are a cornerstone of
polymorphic behavior and are widely used in systems that need to handle different types of objects in a generic
and flexible way.

You might also like