Methods - Tryhardtocarry/2143-oop GitHub Wiki
A method is a function that is defined inside a class and operates on its objects.
Methods allow objects to perform actions, modify attributes, and return values
#include <iostream>
using namespace std;
class Car {
private:
string brand;
string model;
int speed;
public:
// Constructor (Method)
Car(string b, string m) {
brand = b;
model = m;
speed = 0; // Default speed
}
// Method to set speed
void setSpeed(int s) {
if (s >= 0) {
speed = s;
} else {
cout << "not v" << endl;
}
}
// Method to accelerate
void accelerate() {
speed += 10;
cout << brand << " " << model << " accelerated to " << speed << " mph." << endl;
}
// Method to display car details
void display() {
cout << "Car: " << brand << " " << model << ", Speed: " << speed << " mph" << endl;
}
};
int main() {
// Creating Car objects
Car car1("Toyota", "Camry");
Car car2("Ford", "Mustang");
car1.display();
car2.display();
// Using methods
car1.setSpeed(30);
car1.accelerate();
car2.accelerate();
return 0;
}