constructores-destructores-en-cpp

Constructors and Destructors in C++

  • 4 min

A constructor is a special function member of a class that is automatically invoked when an object of that class is created.

Constructors have the same name as the class and do not have a return type (not even void).

Their main purpose is to initialize the class members and perform any necessary configuration to ensure that objects start in a valid state.

If you want to learn more, check out the Object-Oriented Programming Course.

Constructor Syntax

The basic syntax of a constructor is simply the class name itself. For example, this is how we can define a constructor without parameters.

class MyClass {
public:
   MyClass() {
	   // Default initialization
   }
};
Copied!

In this case, we have a constructor for MyClass without any parameters.

But we can also have constructors with one or more arguments, which allows us to initialize an object with values provided as arguments. For example.

class MyClass {
private:
   int x;
public:
   MyClass(int val) : x(val) {
	   // Initialization with a value
   }
};
Copied!

In this case, we have a constructor that receives val, and we use this value to initialize the private member x using the syntax :x(val).

Default Constructor

Every class must have a constructor. If we don’t define one, the compiler will provide one automatically (without parameters or actions).

However, if you define a constructor with parameters, the default constructor will not be generated automatically.

Member Initialization

Constructors allow initializing class members using an initialization list. This is preferable to initialization inside the constructor body, especially for constant members or references.

class MyClass {
private:
    int x;
    const int y;
public:
    MyClass(int a, int b) : x(a), y(b) {}
};
Copied!

Constructor Overloading

Constructor overloading means we can have multiple constructors with different signatures (number of parameters and/or parameter types), and the compiler will select the appropriate constructor based on the arguments passed when creating an object.

Constructor overloading works similarly to function overloading.

#include <iostream>
using namespace std;

class Person {
public:
    string name;
    int age;

	// Constructor with one parameter (only name)
    Person(string n) {
        name = n;
        age = 0;
    }

    // Constructor with two parameters (name and age)
    Person(string n, int e) {
        name = n;
        age = e;
    }
};

Person p1("Luis");
Person p2("Ana", 25);
}
Copied!

In the example,

  • The first constructor receives the name and sets a default age (0).
  • The second constructor receives both the name and the age and assigns those values to the object’s properties.

Other Types of Constructors

Destructors in C++

A destructor is a special function member of a class that is automatically invoked when an object goes out of scope (i.e., when it is “destroyed”).

Unlike constructors, destructors do not accept parameters or return values.

Their main purpose is to release any resources the object may have acquired during its lifetime.

The name of a destructor is the class name preceded by a tilde (~). For example:

class MyClass {
private:
    int* data;
public:
    MyClass(int size) : data(new int[size]) {
        // Initialization
    }
    
    ~MyClass() {
        delete[] data; // Free the resource
    }
};
Copied!

In this example, the destructor frees the dynamically allocated memory when the MyClass object is destroyed.