Answer to Question #322440 in C++ for Harsh

Question #322440

What is the application of Function overloading and Function Overriding? How do we achieve this? Write programme to demonstrate the use of both features.




1
Expert's answer
2022-04-02T09:59:58-0400

Function overloading is a feature of object oriented programming where two or more functions can have the same name but different parameters.


It can be achieved by declaring more than one function has the same name but with different numbers and types of parameters.


Function overriding in C++ is a feature of object oriented programming that allows us to use a function in the child class that is already present in its parent class. 


Program that demonstrate the use of both features:


#include <iostream>
#define PI 3.14
using namespace std;

// Overloaded functions
int trianglePerimeter(int, int, int);
double trianglePerimeter(double, double, double);

class Rectangle
{
private:
	double x;
	double y;

public:
	Rectangle() {};

	Rectangle(double _x, double _y) : x(_x), y(_y) {}

	virtual void printPerimeter()
	{
		cout << "Perimeter of the rectangle: " << (x * 2) + (y * 2) << endl;
	}

	~Rectangle() {};
};

class Circle : public Rectangle
{
private:
	double r;

public:
	Circle(double _r) : r(_r) {}

	// Overriding function
	void  printPerimeter()
	{
		cout << "Perimeter of the circle: " << 2 * PI * r << endl;
	}
};

int main()
{
	Rectangle rectangle(4, 5);
	Circle circle(5.5);

	cout << trianglePerimeter(4, 5, 8) << endl;
	cout << trianglePerimeter(6.5, 5.45, 7.25) << endl;
	rectangle.printPerimeter();
	circle.printPerimeter();

    return 0;
}

// First overloaded function
int trianglePerimeter(int a, int b, int c)
{
	cout << "Perimeter of the triangle: ";

	return a + b + c;
}

// Second overloaded function
double trianglePerimeter(double a, double b, double c)
{
	cout << "Perimeter of the triangle: ";

	return a + b + c;
}




Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS