Virtual and Override:

  1. Virtual: You use 'virtual' keyword with the function in the base class that is to be overridden in the derived class
  2. Override: You use 'override' keyword with the function that is being overridden in the derived class.
  3. This shows an error during compile-time when the names of virtual and override functions are not same.
  4. Example:
    class base
    {
    public:
        virtual void print() { cout << "This is a base function\n"; }
    };

    class derived : public base
    {
    public:
        void print() override { cout << "This is an overridden function\n"; }
    };
Practice 1:

// Write a C++ program to demonstrate single inheritance by creating a base class "Circle" with a member
// function to calculate the area of circle and a derived class "new_Circle" to calculate the area of a circle
// if radius is positive and print a messege if radius is negative.

#include <iostream>
using namespace std;
class Circle
{
protected:
    float radius;

public:
    Circle(float rad = 0) { radius = rad; }
    virtual float calc_Area();
};
float Circle ::calc_Area() { return (3.14 * radius * radius); }

class new_Circle : public Circle
{
public:
    new_Circle(float rad = 0) { radius = rad; }
    float calc_Area() override;
};
float new_Circle ::calc_Area()
{
    if (radius < 0)
    {
        cout << "Radius should not be negative\n";
        return 0.0;
    }
    else
    {
        return (3.14 * radius * radius);
    }
}

int main()
{
    new_Circle c1(5.4);
    cout << "Area of circle: " << c1.calc_Area() << endl;
    return 0;
}




















Comments

Popular posts from this blog

215: Create a C++ program that uses single inheritance to model a simple shape hierarchy. Implement a base class "Shape" with a virtual function "printArea." Derive classes "Rectangle" and "Triangle" from "Shape" and override the "printArea" function to calculate and display their respective areas.

42: ***(Syntax)*** Calculating number of characters and spaces in a string 1- Make a program to calculate the number of characters in a string 2- Modify this and also tell how many spaces are there in that sentence

96: ***(Syntax)*** Functions and Global Variables