Introduction to Classes and Objects
Object-oriented programming (OOP) is a programming paradigm that revolves around the concept of “objects,” which can be instances of classes. A class is a blueprint for creating objects, encapsulating data and the methods that operate on the data.
Defining Classes
Let’s create a simple class called Car
:
#include
#include
class Car {
public:
// Data members (attributes)
std::string brand;
std::string model;
int year;
// Member function (method)
void displayInfo() {
std::cout << "Brand: " << brand << ", Model: " << model << ", Year: " << year << std::endl;
}
};
In this example, Car
has data members (brand
, model
, and year
) and a member function (displayInfo
) to display information about a car.
Creating Objects
Now, let’s create objects of the Car
class:
int main() {
// Create objects of the Car class
Car myCar;
Car anotherCar;
// Set attributes for the first car
myCar.brand = "Toyota";
myCar.model = "Camry";
myCar.year = 2022;
// Set attributes for the second car
anotherCar.brand = "Honda";
anotherCar.model = "Civic";
anotherCar.year = 2021;
// Call member functions to display information
std::cout << "Information about my car:" << std::endl;
myCar.displayInfo();
std::cout << "Information about another car:" << std::endl;
anotherCar.displayInfo();
return 0;
}
In this example, we create two objects (myCar
and anotherCar
) of the Car
class, set their attributes, and call the displayInfo
method to display information about each car.
Exercise: Create and Use Classes
Now, let’s practice creating and using classes in C++.
Conclusion
Feel free to modify the Car
class or create additional classes with different attributes and methods. This exercise will provide hands-on experience with classes and objects in C++.
Understanding classes and objects in C++ is fundamental to mastering object-oriented programming, enabling you to structure your code in a modular and organized manner. Happy coding!