C++ objects
Created By: chatGPT
In C++, an object is an instance of a class. It encapsulates both data and methods that operate on the data. When you create an object, you specify the class from which it derives the attributes and behaviors. Understanding objects is crucial for using object-oriented programming effectively.
// Define a class
class Car {
public:
// Attributes
string brand;
string model;
int year;
// Method to display car details
void display() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}
};
// Create an object of the class
Car myCar;
myCar.brand = "Toyota";
myCar.model = "Corolla";
myCar.year = 2020;
// Call the method to display details
myCar.display();
When defining a class, you can create constructors to initialize objects. Constructors are special methods that are automatically called when an object is created. You can also implement destructors to free resources when the object goes out of scope.
// Class with constructor
class Car {
public:
string brand;
string model;
int year;
// Constructor
Car(string b, string m, int y) {
brand = b;
model = m;
year = y;
}
// Method
void display() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}
};
// Creating an object using the constructor
Car myCar("Honda", "Civic", 2019);
myCar.display();
C++ supports access specifiers to control access to class members. The most common are private, protected, and public. Members declared as private can only be accessed from within the class itself, while public members can be accessed from anywhere in the code.
// Class with access specifiers
class Car {
private:
string brand;
public:
string model;
int year;
// Constructor
Car(string b, string m, int y) {
brand = b;
model = m;
year = y;
}
// Method to access private member
void display() {
cout << "Brand: " << brand << endl;
cout << "Model: " << model << endl;
cout << "Year: " << year << endl;
}
};