codegurukool.com · Free coding tutorials & online compiler

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;
}

Run this code in the online editor

← C++ class methodsC++ access specifiers and encapsulation →