Q.2 Solution......

Q.2 Explain Virtual and Pure Virtual function with example.

Solution :- 

Virtual and Pure Virtual Functions in C++

In Object-Oriented Programming (OOP), the concept of polymorphism allows the same function name to behave differently depending on the type of object that calls it. In C++, this is mainly achieved through virtual functions and pure virtual functions.

1. Virtual Function

  • A virtual function is a member function in a base class that can be overridden in the derived class.

  • It is declared using the keyword virtual inside the base class.

  • When a base class pointer points to a derived class object, calling a virtual function ensures that the derived class version of the function is executed (this is called runtime polymorphism or dynamic binding).

Example: Virtual Function


#include <iostream>
using namespace std;

class Animal {
public:
    virtual void sound() {    // Virtual function
        cout << "Animal makes a sound" << endl;
    }
};

class Dog : public Animal {
public:
    void sound() override {
        cout << "Dog barks" << endl;
    }
};

int main() {
    Animal* a;        // Base class pointer
    Dog d;

    a = &d;           // Pointing to derived class object
    a->sound();       // Calls Dog's version due to virtual function

    return 0;
}

2. Pure Virtual Function

  • A pure virtual function is a virtual function that has no definition in the base class.

  • It is declared by assigning = 0 at the end of the function declaration.

  • A class containing at least one pure virtual function is called an Abstract Class.

  • Objects cannot be created from abstract classes; they only serve as blueprints for derived classes.

  • Derived classes must override pure virtual functions; otherwise, they also become abstract.

Example: Pure Virtual Function


#include <iostream>
using namespace std;

class Shape {
public:
    // Pure virtual function
    virtual void draw() = 0;
};

class Circle : public Shape {
public:
    void draw() override {
        cout << "Drawing a Circle" << endl;
    }
};

class Square : public Shape {
public:
    void draw() override {
        cout << "Drawing a Square" << endl;
    }
};

int main() {
    Shape* s;          // Base class pointer

    Circle c;
    Square sq;

    s = &c;
    s->draw();         // Calls Circle's draw()

    s = &sq;
    s->draw();         // Calls Square's draw()

    return 0;
}

Leave a Reply

Your email address will not be published. Required fields are marked *