๐ŸŽ“ A1Learner
๐Ÿ”

C++ Constructors

A constructor is a special method with the same name as its class. A constructor runs when an object is made.

A constructor with no parameters

The Box constructor fills both members when an object is made. The values print after creation.

#include <iostream>

class Box {
public:
  int width;
  int height;
  Box() {
    width = 4;
    height = 3;
  }
};

int main() {
  Box b;
  std::cout << b.width << std::endl;
  std::cout << b.height << std::endl;
  return 0;
}

A constructor with parameters

Each object passes its own values to the constructor. The two objects print different sizes.

#include <iostream>

class Box {
public:
  int width;
  int height;
  Box(int w, int h) {
    width = w;
    height = h;
  }
};

int main() {
  Box small(2, 3);
  Box large(5, 6);
  std::cout << small.width << " " << small.height << std::endl;
  std::cout << large.width << " " << large.height << std::endl;
  return 0;
}

A constructor prints when it runs

The Stamp constructor prints a line as it runs. That line appears before the first print in main.

#include <iostream>

class Stamp {
public:
  Stamp() {
    std::cout << "Object made" << std::endl;
  }
};

int main() {
  Stamp s;
  std::cout << "Main prints after" << std::endl;
  return 0;
}

Example

#include <iostream>

class Car {
public:
  int year;
  Car(int y) {
    year = y;
  }
};

int main() {
  Car first(2019);
  Car second(2024);
  std::cout << first.year << std::endl;
  std::cout << second.year << std::endl;
  return 0;
}

Key points

  • A constructor has the same name as its class.
  • A constructor has no return type.
  • A constructor runs when an object is made.
  • A constructor can fill members with default values.
  • A constructor can take parameters and fill members from them.
  • Values for a constructor go in parentheses after the object name.

In this example, the Car constructor takes a year as a parameter. Each object passes a different year when it is made. The print lines show that each car kept its own year.

Note

A class can rely on a constructor to leave every new object ready to use.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

When does a constructor run?