Pure Virtual Function | Abstract Class
Pure Virtual Function
A pure virtual function (or abstract function) in C++ is a virtual function for which we can have implementation, But we must override that function in the derived class, otherwise the derived class will also become abstract class (For more info about where we provide implementation for such functions refer to this https://stackoverflow.com/questions/2089083/pure-virtual-function-with-implementation). A pure virtual function is declared by assigning 0 in declaration. See the following example.- CPP
A pure virtual function is implemented by classes which are derived from a Abstract class. Following is a simple example to demonstrate the same.
- CPP
Output:
fun() called
Abstract Class
By definition, an abstract class in C++ is a class that has at least one pure virtual function (i.e., a function that has no definition). The classes inheriting the abstract class must provide a definition for the pure virtual function; otherwise, the subclass would become an abstract class itself.
Abstract classes are essential to providing an abstraction to the code to make it reusable and extendable. For example, a Vehicle parent class with Truck and Motorbike inheriting from it is an abstraction that easily allows more vehicles to be added. However, even though all vehicles have wheels, not all vehicles have the same number of wheels – this is where a pure virtual function is needed.
Consider an example of a Shape
base class with sub-classes (Triangle
and Rectangle
) that inherit the Shape
class.
Now, suppose we need a function to return the area of a shape. The function will be declared in the Shape
class; however, it cannot be defined there as the formula for the area is different for each shape. A non-specific shape does not have an area, but rectangles and triangles do. Therefore, the pure virtual function for calculating area will be implemented differently by each sub-class.
The following code snippet implements the abstract Shape
class along with its sub-classes:
Note: The return type of the virtual function must be consistent throughout all of its implementing classes.
1) A class is abstract if it has at least one pure virtual function.
2) We can have pointers and references of abstract class type.
For example the following program works fine.
- CPP
In Derived3) If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
The following example demonstrates the same.
- CPP
Compiler Error: cannot declare variable 'd' to be of abstract type 'Derived' because the following virtual functions are pure within 'Derived': virtual void Base::show()4) An abstract class can have constructors.
For example, the following program compiles and runs fine.
- CPP
0 Response to "Pure Virtual Function | Abstract Class | OOPS | C++"
Post a Comment
If you have any doubts, please let me know...