April 20, 2023

Pure Virtual Functions

Posted on April 20, 2023  •  2 minutes  • 395 words

In C++, a pure virtual function is a virtual function that is declared in a base class but does not provide an implementation.

Syntax:

virtual return_type functionName(parameters) = 0;

Where = 0 at the end of the declaration indicates that the function is pure virtual.

A class that contains one or more pure virtual functions is called an abstract class, and it cannot be instantiated (can not create an object for this class). Instead, you must derive a new class from the abstract class and provide an implementation for all the pure virtual functions in the derived class.

Consider the Shape class

class Shape
{
public:
    virtual double getArea() = 0;
};

This class defines a pure virtual function called “getArea()” that has no implementation. Therefore, you cannot create an instance of the Shape class directly. Instead, you must create a derived class that provides an implementation for the “getArea()” function:

class Circle : public Shape
{
public:
    Circle(double rad){
        radius = rad;
    }
    double getArea(){
        return (3.14 * radius * radius);
    }
private:
    double radius;
};

The derived class “Circle” provides an implementation for the “getArea()” function and can be instantiated. Because “Circle” inherits from the “Shape” class, it also inherits the pure virtual function “getArea()”, which must be implemented in the derived class.

Pure virtual functions are often used to create interfaces or abstract classes that define a set of functions that must be implemented by any derived class.

This allows for more flexible and modular code, since you can write code that depends only on the interface, without knowing the specific implementation of the derived class.

Example Code:

#include<iostream>

class Shape
{
public:
    virtual double getArea() = 0;
    virtual double getPerimeter() = 0;
    virtual std::string getName() = 0;
};

class Rectangle : public Shape
{
public: 
    Rectangle(){
        length = 0.0;
        width = 0.0;
    }
    Rectangle(double len, double wid){
        length = len;
        width = wid;
    }
    double getArea(){
        return (length * width);
    }
    double getPerimeter(){
        return (2 * (length + width));
    }
    std::string getName(){
        return "Rectangle";
    }
protected:
    double length, width;
};

class Square : public Rectangle
{
public:
    Square(double side){
        length = side;
        width = side;
    }

    std::string getName(){
        return "Square";
    }   
};

int main(int argc, char const *argv[])
{
    Rectangle r1(10,5);
    std::cout << r1.getArea() << std::endl;

    Square s(100);
    std::cout << s.getArea() << std::endl;
    std::cout << s.getName() << std::endl;

    return 0;
}
Follow me

I work on everything coding and share developer memes