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

153: Write a program to read an amount (integer value) and break the amount into smallest possible number of bank notes. Note: The possible banknotes are 500, 100, 50, 20, 10, 5, 2, and 1

206: Write a program to create a class named "Circle" which has the property "radius". Define functions to calculate the area and circumference of the circle.

221: // In Task 2, we discussed multilevel inheritance with parameterized constructors for Student, UndergraduateStudent, and GraduateStudent classes in a university management system. Can you explain the advantages of using multilevel inheritance with specific details about the functions and data members in these classes? How were the parameterized constructors (e.g., setting student name, age, and ID) used to ensure that each class in the hierarchy correctly initializes its properties, such as creating an UndergraduateStudent named "John," aged 20, with a student ID of 12345