Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
A pure virtual function in C++ is a virtual function for which we can have an implementation, and it is necessary to override the function in the derived class otherwise, this derived class will become an abstract class too.
Pure virtual functions in C++ are virtual functions with no definition. We use the keyword "virtual" in C++ to declare a virtual function. They are assigned a value of zero when they are declared.
What is Pure Virtual Function in C++?
A pure virtual function in C++ is a virtual function declared in a base class that must be overridden in all derived classes. It is specified by assigning = 0 to the function declaration. Classes containing pure virtual functions are called abstract classes and cannot be instantiated.
Syntax of Pure Virtual functions
virtual void f() = 0;
Although pure virtual functions can be given a small definition inside the abstract class, which we want all the derived classes to have, we can still not create objects of an abstract class. They must be defined outside the class definition; otherwise, the compiler will give an error. The inline pure virtual definition is illegal.
// Derived class (inherits the pure virtual function) class iPhone: public phone { string model_name; public: // implementation of the test function void test() { cout << "Test function up and running "; } };
int main(void) { iPhone obj; obj.test(); return 0; }
You can also try this code with Online C++ Compiler
Used to define an interface without providing a default implementation.
Allows polymorphic behavior in derived classes.
Cannot be instantiated on its own.
Example of Pure Virtual Function in C++
class Shape {
public:
virtual void draw() = 0; // Pure virtual function
};
class Circle : public Shape {
public:
void draw() override {
// Implementation of draw for Circle
}
};
This code defines a class hierarchy for geometric shapes in C++. The Shape class serves as an abstract base class with a pure virtual function draw(), denoted by = 0, indicating that it has no implementation in the base class and must be overridden by derived classes. This makes Shape an abstract class, meaning it cannot be instantiated on its own, but provides a common interface for its derived classes.
The Circle class inherits from Shape and overrides the draw() function with its own implementation, specifying how a circle should be drawn. This allows Circle objects to be treated as Shape objects and ensures polymorphic behavior.
Similarities between Virtual Function and Pure Virtual Function in C++
Both enable polymorphism and dynamic binding.
Both can be overridden in derived classes.
Both require at least one derived class to provide an implementation.
Advantages of Pure Virtual Functions
Enables the creation of abstract base classes.
Forces derived classes to implement specific functionality.
Provides a clean interface for derived classes to adhere to.
Facilitates polymorphic behavior and runtime polymorphism.
Supports design patterns like the Factory Method and Template Method.
Differences between Virtual Function and Pure Virtual Function in C++
Parameters
Virtual Function
Pure Virtual Function
Definition
A function that is declared in the base class and can be overridden in derived classes.
A function that is declared in the base class but has no implementation and must be overridden in derived classes.
Implementation
Has a default implementation in the base class.
Does not have an implementation in the base class.
Purpose
Used to achieve runtime polymorphism.
Used to make a class abstract and force derived classes to provide an implementation.
Class Type
Can be used in both regular and abstract classes.
Only used in abstract classes.
Must Be Overridden?
Not necessarily; can have a default implementation.
Must be overridden in any derived class.
Syntax
virtual void func();
virtual void func() = 0;
Inheritance
Derived classes can override it or use base class implementation.
Derived classes must override it.
Role of Pure Virtual Functions in Abstract class
An abstract class is a class that must have at least one pure virtual function.
Example-1
C++
C++
#include using namespace std; class abstractExample { int x; public: virtual void display() = 0; int getX() { return x; } }; int main(void) { abstractExample obj; return 0; }
You can also try this code with Online C++ Compiler
cannot declare variable 'obj' to be of abstract type 'abstractExample'
abstractExample obj;
^~~
because the following virtual functions are pure within 'abstractExample':
class abstractExample
^~~~~~~~~~~~~~~
'virtual void abstractExample::display()'
virtual void display() = 0;
^~~~~~~
Pointers and references of an abstract class can be created though an abstract class cannot be instantiated.
Example-2
C++
C++
#include<iostream> using namespace std;
class abstractBase { public: virtual void display() = 0; };
class abstractDerived: public abstractBase { public: void display() { cout << "Inside the derived class"; } };
int main(void) { abstractBase *obj = new abstractDerived(); obj->display(); return 0; }
You can also try this code with Online C++ Compiler
It's necessary for all the classes derived from the base class to implement all the pure virtual functions of the base class, or else they will become abstract too.
Example-3
C++
C++
#include<iostream> using namespace std; class abstractBase { public: virtual void display() = 0; };
class abstractDerived : public abstractBase { };
int main(void) { abstractDerived obj; return 0; }
You can also try this code with Online C++ Compiler
Compiler Error: cannot declare variable 'obj' to be of abstract type
'abstractDerived' because the following virtual functions are pure within
'abstractDerived': virtual void abstractBase::display()
An abstract class can have constructors.
Example-4
C++
C++
#include<iostream> using namespace std;
// Abstract class with a constructor class Base { protected: int x; public: virtual void display() = 0; Base(int val){ x = val; cout<<"From inside the constructor of Base class \n"; } };
class Derived: public Base { int y; public: Derived(int i, int j):Base(i) { y = j; } void display(){ cout << "x = " << x << ", y = " << y<<'\n'; } };
int main(void) { Derived obj1(9, 1); obj1.display();
// creating an object using pointer of base class Base *ptr=new Derived(3,4); ptr->display();
return 0; }
You can also try this code with Online C++ Compiler
From inside the constructor of Base class
x = 9, y = 1
From inside the constructor of Base class
x = 3, y = 4
The abstract class has a pure virtual function and can have normal functions and variables like any other class.
They are mainly used for the purpose of upcasting so that all of the derived classes can use its interface.
Objects of an abstract class cannot be created as a slot is reserved for the pure function in Vtable, but it remains incomplete as there are no addresses in the Vtable.
Frequently Asked Questions
What is a virtual function in C++?
A virtual function in C++ is a function in the base class that can be overridden by derived classes to support runtime polymorphism.
Can you call a pure virtual function?
You cannot directly call a pure virtual function, as it has no implementation in the base class and must be overridden in derived classes.
Why is pure virtual function initialized by 0?
A pure virtual function is initialized with = 0 in C++ to indicate it has no implementation in the base class. This syntax explicitly marks the function as "pure," requiring derived classes to override it, ensuring the base class acts as an abstract class.
Conclusion
In this article, we have extensively discussed Pure Virtual Function in C++. This function serve as powerful tools for creating abstract base classes and defining interfaces that enforce specific behaviors in derived classes. By declaring a function as pure virtual, with "= 0", it mandates derived classes to provide their own implementation, facilitating polymorphic behavior and enabling the use of dynamic binding