Home › C++ Tutorial › C++ constructors
C++ constructors
Run when an object is created.
A constructor has the class name and no return type. Use an initializer list to set fields, and a destructor ~Name() for cleanup.
Example code
#include <iostream>
using namespace std;
class Car {
public:
string brand; int year;
Car(string b, int y) : brand(b), year(y) {}
~Car() { cout << "bye " << brand << endl; }
};
int main() {
Car c("Tata", 2024);
cout << c.brand << " " << c.year << endl;
return 0;
}