C++ Tutorial

Class and Object

Reference

Inheritance and Derivation

Polymorphism and Virtual Functions

Operator Overloading

Template

Exception

Object Oriented Advanced

Input/Output Stream

File Operations

Virtual Functions Notes and Polymorphism Constituting Conditions in C++

In this tutorial, we will learn about C++ virtual functions and their role in achieving runtime polymorphism. Polymorphism is an important concept in object-oriented programming that allows objects of different classes to be treated as objects of a common base class. Virtual functions are key to achieving runtime polymorphism in C++.

  • Virtual functions:

Virtual functions are member functions declared with the virtual keyword in the base class. A derived class can override a virtual function to provide its own implementation. When a pointer or reference to a base class is used to call a virtual function, the appropriate implementation is chosen based on the actual type of the object pointed to or referred to at runtime.

Here's an example demonstrating the basic usage of virtual functions:

#include <iostream>

class Base {
public:
    virtual void print() {
        std::cout << "Base class" << std::endl;
    }
};

class Derived : public Base {
public:
    void print() override {
        std::cout << "Derived class" << std::endl;
    }
};

int main() {
    Base* basePtr = new Derived();
    basePtr->print(); // Output: Derived class
    delete basePtr;
    return 0;
}
  • Conditions for constituting polymorphism:

In order to achieve runtime polymorphism, the following conditions must be met:

  • A base class must define a virtual function.
  • A derived class must override the virtual function.
  • You must use a base class pointer or reference to call the virtual function.

Let's analyze the above example in the context of these conditions:

  • We declared the print function in the Base class as virtual.
  • We provided an overriding implementation for the print function in the Derived class using the override keyword.
  • We used a Base pointer (basePtr) to call the print function, which chose the appropriate implementation based on the runtime type of the object pointed to (in this case, Derived).

By following these conditions, we were able to achieve runtime polymorphism.

  • Notes on virtual functions:
  • The virtual keyword is only required in the base class declaration. However, you can use the override keyword in the derived class to explicitly indicate that the function is intended to override a virtual function from the base class. The override keyword also helps the compiler detect any errors related to function signatures.
  • If a derived class does not provide an overriding implementation for a virtual function, the base class implementation will be used.
  • If a class contains at least one pure virtual function (declared with = 0), it becomes an abstract class and cannot be instantiated. Derived classes must provide implementations for all pure virtual functions to be instantiable.

That's it for our C++ virtual functions and polymorphism tutorial. Virtual functions are essential for achieving runtime polymorphism in C++, enabling you to write more flexible, reusable, and maintainable code in your object-oriented programs.

  1. C++ virtual functions explained:

    #include <iostream>
    
    class Base {
    public:
        // Virtual function
        virtual void display() const {
            std::cout << "Base class display" << std::endl;
        }
    };
    
    class Derived : public Base {
    public:
        // Override virtual function
        void display() const override {
            std::cout << "Derived class display" << std::endl;
        }
    };
    
    int main() {
        Derived derivedObj;
        Base* basePtr = &derivedObj;
    
        // Calls the appropriate display method based on the actual type
        basePtr->display();
    
        return 0;
    }
    
    • Virtual functions enable polymorphism by allowing derived classes to provide specific implementations.
  2. How to use virtual functions for polymorphism in C++:

    #include <iostream>
    
    class Shape {
    public:
        // Virtual function for polymorphism
        virtual void draw() const {
            std::cout << "Drawing a shape" << std::endl;
        }
    };
    
    class Circle : public Shape {
    public:
        // Override virtual function
        void draw() const override {
            std::cout << "Drawing a circle" << std::endl;
        }
    };
    
    class Square : public Shape {
    public:
        // Override virtual function
        void draw() const override {
            std::cout << "Drawing a square" << std::endl;
        }
    };
    
    int main() {
        Circle circle;
        Square square;
    
        // Polymorphic behavior
        Shape* shapes[] = {&circle, &square};
    
        for (const auto& shape : shapes) {
            shape->draw();
        }
    
        return 0;
    }
    
    • Virtual functions enable polymorphic behavior, allowing objects of different derived types to be treated uniformly.
  3. C++ pure virtual functions and abstract classes:

    #include <iostream>
    
    class Shape {
    public:
        // Pure virtual function makes the class abstract
        virtual void draw() const = 0;
    };
    
    class Circle : public Shape {
    public:
        // Override pure virtual function
        void draw() const override {
            std::cout << "Drawing a circle" << std::endl;
        }
    };
    
    int main() {
        // Cannot create an instance of an abstract class
        // Shape shape; // Error: cannot instantiate abstract class
    
        Circle circle;
        circle.draw();
    
        return 0;
    }
    
    • Pure virtual functions make a class abstract, and objects of abstract classes cannot be instantiated.