Classes and Objects - EduardoMSU/OOP-2143 GitHub Wiki
In object-oriented programming, classes and objects form the foundation of the paradigm.
- Class: A blueprint or template for creating objects. It defines the properties (attributes) and behaviors (methods) that the objects of the class will have.
- Object: An instance of a class. It represents a specific realization of the class blueprint, with its own values for the attributes defined in the class.
Feature | Class | Object |
---|---|---|
Definition | A blueprint for creating objects that defines attributes and methods. | An instance of a class with specific values assigned to its attributes. |
Purpose | To define the structure and behavior of objects. | To represent and manipulate real-world entities using the class structure. |
Memory | Does not occupy memory until an object is created. | Occupies memory when instantiated. |
Relationship | Acts as a template for creating objects. | Is a realization of the class. |
Accessibility | Includes access modifiers (public , private , etc.) to control access to attributes. |
Accesses class-defined methods and attributes based on the object's state. |
#include <iostream>
#include <string>
// Define a class
class Car {
private:
std::string brand; // Attribute: Brand of the car
int speed; // Attribute: Current speed of the car
public:
// Constructor
Car(const std::string& carBrand, int initialSpeed) : brand(carBrand), speed(initialSpeed) {}
// Method to display car details
void displayDetails() const {
std::cout << "Brand: " << brand << ", Speed: " << speed << " km/h" << std::endl;
}
// Method to accelerate the car
void accelerate(int increment) {
speed += increment;
std::cout << "The car accelerates. New speed: " << speed << " km/h" << std::endl;
}
// Method to apply brakes
void applyBrakes(int decrement) {
speed -= decrement;
if (speed < 0) speed = 0;
std::cout << "The car slows down. New speed: " << speed << " km/h" << std::endl;
}
};
int main() {
// Create an object of the Car class
Car myCar("Toyota", 50);
// Call methods on the object
myCar.displayDetails();
myCar.accelerate(20);
myCar.applyBrakes(30);
myCar.displayDetails();
return 0;
}