Practical 15- Virtual and Pure Virtual Functions
Practical 15- Virtual and Pure Virtual Functions
In C++, a virtual function is a function that is defined in the base class and can be overridden
in derived classes. It ensures that the correct function is called for an object, regardless of
the type of reference (or pointer) used for the function call.
A pure virtual function is a virtual function that has no implementation in the base class and
must be overridden in any derived class. It makes the base class abstract, meaning you
cannot instantiate objects of the base class directly.
cpp
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// Virtual function
virtual void draw() {
cout << "Drawing Shape" << endl;
}
// Virtual destructor
virtual ~Shape() {}
};
// Derived class
class Circle : public Shape {
private:
double radius;
public:
Circle(double r) : radius(r) {}
1/4
cout << "Drawing Circle" << endl;
}
// Derived class
class Square : public Shape {
private:
double side;
public:
Square(double s) : side(s) {}
int main() {
// Create objects of derived classes
Circle c(5);
Square s(4);
2/4
cout << "Area of Circle: " << shape1->area() << endl; // Outputs: Area of
Circle: 78.53975
cout << "Area of Square: " << shape2->area() << endl; // Outputs: Area of
Square: 16
return 0;
}
Explanation:
1. Base class Shape :
Contains a pure virtual function area() , which forces derived classes to implement
it.
Implement the area() function to calculate the area for each shape.
3. Main function:
Output:
mathematica
Drawing Circle
Drawing Square
Area of Circle: 78.53975
Area of Square: 16
Key Concepts:
Virtual Function: Ensures the correct function is called according to the object type,
even if the reference or pointer is to the base class.
3/4
Pure Virtual Function: Makes the base class abstract and forces derived classes to
implement the function.
4/4