In object-oriented programming, an object is a fundamental unit that encapsulates three core characteristics: identity, state, and behavior.
Identity: This is the unique property that distinguishes one object from another. Even if two objects have identical states, their identities are distinct, allowing the system to differentiate between them.
State: The state of an object comprises all its properties and their current values. It represents the data held by the object at any given moment.
Behavior: Behavior refers to the set of methods or functions that define what an object can do. These methods operate on the object's state and can modify it, enabling the object to perform specific tasks or respond to certain events.
To illustrate these concepts in C++, consider a simple example of a TrafficLight class:
cpp
#include <iostream>
#include <string>
// TrafficLight class definition
class TrafficLight {
private:
std::string color; // State: current color of the traffic light
public:
// Constructor to initialize the traffic light with a color
TrafficLight(const std::string& initialColor) : color(initialColor) {}
// Method to change the color of the traffic light
void changeColor(const std::string& newColor) {
color = newColor;
}
// Method to display the current color of the traffic light
void displayColor() const {
std::cout << "The traffic light is " << color << "." << std::endl;
}
};
int main() {
// Create a TrafficLight object with initial color "Red"
TrafficLight light("Red");
// Display the current color
light.displayColor(); // Output: The traffic light is Red.
// Change the color to "Green"
light.changeColor("Green");
// Display the new color
light.displayColor(); // Output: The traffic light is Green.
return 0;
}
In this example:
Identity: Each TrafficLight object has a unique identity, even if multiple instances have the same color. This uniqueness allows the program to manage and differentiate between different traffic lights.
State: The color member variable represents the state of the TrafficLight object. It holds the current color (e.g., "Red", "Green") of the traffic light.
Behavior: The TrafficLight class provides methods like changeColor and displayColor. The changeColor method allows the object's state to be modified by changing its color, while displayColor outputs the current state to the console.
By encapsulating state and behavior within the TrafficLight class, this design promotes modularity and maintainability, allowing each object to manage its own state and define its own behavior.