Objective: Write a C++ program to show the implementation of function overloading and function Overriding.
Code:
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// Function to calculate area (Overloaded)
void area(int side) {
cout << "Area of Square: " << side * side << endl;
}
void area(int length, int breadth) {
cout << "Area of Rectangle: " << length * breadth << endl;
}
// Virtual function to demonstrate overriding
virtual void display() {
cout << "This is a shape." << endl;
}
};
// Derived class
class Circle : public Shape {
public:
// Overriding the base class display function
void display() override {
cout << "This is a circle." << endl;
}
// Overloading area function for circle
void area(double radius) {
cout << "Area of Circle: " << 3.14 * radius * radius << endl;
}
};
int main() {
// Demonstrating function overloading
Shape shape;
shape.area(4); // Calls area(int side) - Square
shape.area(5, 6); // Calls area(int length, int breadth) - Rectangle
// Demonstrating function overriding
Circle circle;
shape.display(); // Calls base class display
circle.display(); // Calls derived class display (overridden function)
// Overloading area function in derived class
circle.area(3.5); // Calls area(double radius) - Circle
return 0;
}
Output:
No comments:
Post a Comment