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

88: Using switch statement Write a C program to input marks of five subjects Physics, Chemistry, Biology, Mathematics and Computer. Calculate percentage and grade according to following: // Percentage >= 90% : Grade A Percentage >= 80% : Grade B Percentage >= 70% : Grade C Percentage >= 60% : Grade D Percentage >= 40% : Grade E Percentage < 40% : Grade F

205: Book Catalog: Define a struct to represent a book with attributes like title, author, and publication year. Write a program to create a catalog of books by taking user input and display books published after a certain year.

15: Take input of age and name of 3 people by user and determine oldest and youngest among them with his age. -_-_-_-_-_-_-_-_-(line with spaces input concept)-_-_-_-_-_-_-_-_