Object-Oriented Programming & C++ Function Overloading
Classified in Computers
Written on in English with a size of 2.76 KB
Object-Oriented Programming (OOP) Fundamentals
Object-oriented programming (OOP) is a computer programming model that uses objects to represent and manipulate data.
OOP is well-suited for large, complex, and frequently updated software. Some of the main features of OOP include:
- Classes: User-defined data types that serve as a blueprint for individual objects, attributes, and methods.
- Objects: Instances of a class that are created with specific data.
- Methods: Functions that objects can perform.
- Attributes: Represent the state of an object.
- Abstraction: Exposes only the essential information of an object to the user.
- Polymorphism: Adds different meanings to a single component.
- Inheritance: Allows a class to inherit the properties and methods of another class.
- Constructors and Destructors: Manage the lifecycle of objects.
Function Overloading in C++
Function overloading in C++ is a technique that allows multiple functions to have the same name but different parameters. This enables the programmer to provide different semantics for a function depending on the number and types of its arguments.
Here are some examples of function overloading:
Print Function
A print function that takes a std::string
argument might perform different tasks than a function that takes a double
argument.
Plus Function
A function that can add numbers of different types, such as int
and double
.
Area Function
A function that can calculate the area of a rectangle, with default values for the width and height, but also allows the caller to provide different values.
Function overloading can help to:
- Speed up program execution
- Make code easier to understand
- Reduce memory utilization
- Make programs reusable
C++ Code Example: Time Class
#include <iostream>
using namespace std;
class time {
private:
int hours;
int minutes;
public:
void gettime(int h, int m) {
hours = h;
minutes = m;
}
void puttime() {
cout << "Hours: " << hours << " Minutes: " << minutes << endl;
}
void sum(time, time);
};
void time::sum(time t1, time t2) {
minutes = t1.minutes + t2.minutes;
hours = minutes / 60;
minutes %= 60;
hours = hours + t1.hours + t2.hours;
}
int main() {
time t1, t2, t3;
t1.gettime(2, 45);
t2.gettime(3, 30);
t3.sum(t1, t2);
t1.puttime();
t2.puttime();
t3.puttime();
return 0;
}