Saturday, April 19, 2025

C++ OO Pure Virtual Functions

A pure virtual function is a virtual function that has no implementation in the base class and must be overridden by any derived classes that inherit from the base class.  

Pure virtual functions are useful when you have a base class that defines a common interface, but the implementation of the function is left to the derived classes. By making the function pure virtual, you require the derived classes to implement the function and provide their own implementation.

Pure virtual functions are commonly used in abstract base classes, which are classes that are not meant to be instantiated directly, but are designed to be subclassed by other classes that provide the implementation of the pure virtual functions.


#include <iostream>

using namespace std;

class Prim{
    public:
        virtual void printing()=0;
};

class Sec : public Prim{
    public:
        void printing() {
            cout << "I am From Sec Cls" << endl;
        }
};

class Third : public Prim {
    public:
        void printing() {
            cout << "I am from Third Cls" << endl;
        }
};

int main() {

    Third Object;
    Object.printing();

    return 0;
}

This C++ program demonstrates the use of a pure virtual function in a class hierarchy.

In this example, the class Prim contains a pure virtual function called printing(). A pure virtual function is declared with the syntax virtual void functionName() = 0; and has no implementation.

Since Prim contains a pure virtual function, it is an abstract class and cannot be instantiated. The classes Sec and Third inherit from Prim and implement the printing() function in their own unique ways.

In the main() function, an object of the Third class is created and its printing() function is called, which outputs the message "I am from Third Cls" to the console.

The use of pure virtual functions allows for polymorphism in C++. By creating a pure virtual function in a base class, we can ensure that all derived classes provide their own implementation of that function.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...