Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Monday, November 4, 2024

Virtual functions and pure virtual functions

Virtual functions and Pure virtual functions 


Virtual functions and pure virtual functions are key components of polymorphism, enabling runtime flexibility in class hierarchies. Here’s a detailed look at each, including their differences, purposes, and how they’re used in object-oriented programming.


Virtual Functions

A virtual function is a function defined in a base class that can be overridden by derived classes. When a function is declared as virtual, it tells the compiler to use dynamic binding (or late binding) for that function. This means that the function to be executed is determined at runtime based on the actual type of the object, not the type of the pointer/reference used to call the function.

Characteristics

  • Declared in Base Class: Defined with the virtual keyword in the base class.
  • Overridable: Derived classes can override this function to provide specific implementations.
  • Dynamic Binding: Allows calling the derived class’s overridden function through a base class pointer/reference at runtime.

Purpose

Virtual functions enable polymorphic behavior, where a base class pointer can call functions of derived classes. This allows flexible and extensible code by providing a common interface that different subclasses can implement differently.

Example of Virtual Function


#include <iostream>
using namespace std;
class Animal {
public:
    virtual void sound() {  // Virtual function
        cout << "Some generic animal sound" << endl;
    }
};
class Dog : public Animal {
public:
    void sound() override {  // Overriding the virtual function
        cout << "Woof!" << endl;
    }
};
class Cat : public Animal {
public:
    void sound() override {  // Overriding the virtual function
        cout << "Meow!" << endl;
    }
};
int main() {
    Animal *animal1 = new Dog();
    Animal *animal2 = new Cat();
    animal1->sound();  // Calls Dog's version of sound()
    animal2->sound();  // Calls Cat's version of sound()
    delete animal1;
    delete animal2;
    return 0;
}

Output:

Woof!
Meow!


In this example, the sound function in the base class Animal is virtual. When sound() is called using a base class pointer, C++ uses dynamic binding to determine the correct version of sound() to call, based on the actual object type (Dog or Cat).


Pure Virtual Functions

A pure virtual function is a virtual function that has no implementation in the base class. It serves as a placeholder that enforces derived classes to provide their own implementations. Declaring a function as pure virtual makes the containing class an abstract class, meaning it cannot be instantiated on its own.

Characteristics

  • Declaration: Declared by assigning = 0 in the function declaration, e.g., virtual void sound() = 0;.
  • No Implementation in Base Class: Has no body in the base class, only in derived classes.
  • Abstract Class Requirement: Classes with pure virtual functions become abstract classes and cannot be instantiated directly.
  • Mandatory Override: Any derived class must implement the pure virtual function, or it will also be considered abstract.

Purpose

Pure virtual functions define an interface that derived classes must adhere to. This is useful for establishing a standard set of functions that all subclasses must implement, ensuring consistent behavior across different implementations.

Example

#include <iostream>
using namespace std;
class Animal {
public:
    virtual void sound() = 0;  // Pure virtual function
};
class Dog : public Animal {
public:
    void sound() override {  // Must override pure virtual function
        cout << "Woof!" << endl;
    }
};
class Cat : public Animal {
public:
    void sound() override {  // Must override pure virtual function
        cout << "Meow!" << endl;
    }
};
int main() {
    Animal *animal1 = new Dog();
    Animal *animal2 = new Cat();
    animal1->sound();  // Calls Dog's version of sound()
    animal2->sound();  // Calls Cat's version of sound()
    delete animal1;
    delete animal2;
    return 0;
}


Output: 

Woof!
Meow!


Differences between Virtual Functions and Pure Virtual Functions

AspectVirtual FunctionPure Virtual Function
DefinitionDeclared with virtual keyword in base classDeclared with virtual keyword and = 0
Implementation in BaseMay have an implementation in the base classNo implementation in the base class
Override RequirementOptional in derived classMandatory in derived class
InstantiationBase class can still be instantiated if no pure virtual functionsBase class becomes abstract and cannot be instantiated
Use CaseAllows customization in derived classesEstablishes a mandatory interface for derived classes

Summary

  • Virtual Function: Has optional overriding; allows polymorphism with optional specific implementations.
  • Pure Virtual Function: Mandates overriding; creates an abstract class to define a required interface.

No comments:

Post a Comment