#include <iostream>
#include <string>
using namespace std;
// Define Car class
class Car {
private:
string color; // Private member variable: color
string model; // Private member variable: model
public:
// Constructor to initialize properties
Car(string c, string m) {
color = c;
model = m;
}
// Public method: display information
void displayInfo() {
cout << "Model: " << model << ", Color: " << color << endl;
}
// Public method: start the car
void start() {
cout << "Car started!" << endl;
}
};
Explanation:
- In the above code, we define the
<span>Car</span>
class, which has two private member variables<span>color</span>
and<span>model</span>
. - The constructor is used to initialize these properties when creating a new object.
- We also define some public methods to access or manipulate these properties, including the display information (
<span>displayInfo</span>
) and start the car (<span>start</span>
) methods.
3. Creating and Using Objects
Once we have defined our <span>Car</span>
class, we can create multiple different objects based on that class. For example:
int main() {
// Create Car object instance
Car myCar("Red", "Ford");
// Call public methods to display information and start the car
myCar.displayInfo();
myCar.start();
return 0;
}
Output:
After executing the above code, the output is as follows:
Model: Ford, Color: Red
Car started!
Explanation:
- In the
<span>main()</span>
function, we instantiated a specific car named<span>myCar</span>
. - Then, we called its public methods to print the vehicle’s information and perform its actions.
4. Encapsulation and Access Control
Encapsulation is a major feature of object-oriented programming. In our example, by using access specifiers, namely public and private, we do not need to expose internal implementation details, only providing the necessary methods for external access. This ensures data security, meaning users cannot directly modify the internal state but can only operate through public methods.
Conclusion:
In C++, by using the concepts of “classes” and “objects”, we can model complex problems more clearly and effectively. Understanding how to build your own custom types and how to use them to carry related information is an important step in developing good programs. Next, you can try to expand this simple model by adding more functionalities (like acceleration, braking, etc.), or further experiment with multiple subclasses to understand advanced topics like inheritance.
I hope this article helps you better understand the concepts of class and object in C++, making programming easier!