Method - EduardoMSU/OOP-2143 GitHub Wiki
A method is a function that is defined within a class in object-oriented programming. Methods define the behavior of objects created from the class and can manipulate the object's attributes (instance variables). Methods are essential to the functionality of a class and allow objects to perform actions or computations.
Characteristic | Description |
---|---|
Defined in a Class | Methods are functions defined inside a class and operate on instances of that class (objects). |
Encapsulation | Methods encapsulate behavior that operates on object data, ensuring that data manipulation is controlled. |
Access Modifiers | Methods can have access modifiers (public , private , protected ) to control their visibility and access. |
Return Type | A method may or may not return a value. If it returns a value, the return type must be specified. |
Parameters | Methods can accept parameters which are passed when the method is called, affecting the behavior of the method. |
#include <iostream>
using namespace std;
class Car {
public:
// Method to display the car details
void displayDetails() {
cout << "Car Details: Make: Toyota, Model: Camry, Year: 2022" << endl;
}
// Method to set the car's speed
void setSpeed(int speed) {
cout << "Car speed is set to " << speed << " km/h" << endl;
}
// Method to calculate fuel efficiency
float calculateEfficiency(int miles, int gallons) {
return (float)miles / gallons;
}
};
int main() {
Car myCar;
myCar.displayDetails(); // Calling method with no parameters
myCar.setSpeed(100); // Calling method with one parameter
float efficiency = myCar.calculateEfficiency(300, 10); // Calling method with return value
cout << "Fuel Efficiency: " << efficiency << " miles per gallon" << endl;
return 0;
}