Labs ICT
โญ Pro Login

Constructors

Constructors

A constructor is a special member function that runs automatically when an object is created. It has the same name as the class and no return type.

Default Constructor

A constructor that takes no arguments. If you don't define any, the compiler generates one.

Parameterized Constructor

A constructor that accepts arguments to initialize an object with specific values.

#include <iostream>
using namespace std;

class Rectangle {
public:
  double width;
  double height;

  Rectangle() {
    width = 1;
    height = 1;
  }

  Rectangle(double w, double h) {
    width = w;
    height = h;
  }

  double area() {
    return width * height;
  }
};

int main() {
  Rectangle r1;
  Rectangle r2(5.0, 3.0);
  cout << "Area r1: " << r1.area() << "\n";
  cout << "Area r2: " << r2.area() << "\n";
  return 0;
}
Try it Yourself โ†’

๐Ÿงช Quick Quiz

What is a constructor?