Constructors and Destructors - Tryhardtocarry/2143-oop GitHub Wiki
Constructors and Destructors in C++
- Constructor is a special method that is automatically called when an object is created.
- A Destructor is a special method that is automatically called when an object is destroyed.
#include <iostream>
using namespace std;
class Car {
private:
string brand;
string model;
public:
// Constructor (called when an object is created)
Car(string b, string m) {
brand = b;
model = m;
}
// Destructor (called when an object is destroyed)
~Car() {
}
// Method to display car details
void display() {
cout << "Car: " << brand << " " << model << endl;
}
};
int main() {
// Creating Car objects
Car car1("Toyota", "Corolla");
Car car2("Honda", "Civic");
car1.display();
car2.display();
}