Virtual and Override:
- Virtual: You use 'virtual' keyword with the function in the base class that is to be overridden in the derived class
- Override: You use 'override' keyword with the function that is being overridden in the derived class.
- This shows an error during compile-time when the names of virtual and override functions are not same.
- 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
Post a Comment