Language: EN

constructores-destructores-en-cpp

Constructors and Destructors in C++

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 setup to ensure that objects begin in a valid state.

Constructor Syntax

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

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

In this case, we have a MyClass constructor 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
   }
};

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 do not 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 automatically generated.

Member Initialization

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

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

Constructor Overloading

Constructor overloading means that we can have multiple constructors with different signatures (number of parameters and/or types of parameters), 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);
}

In the example,

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

Other Types of Constructors

Copy Constructor

It is used to create a new object as a copy of an existing object. It is implicitly generated if no one is defined.

class MyClass {
private:
    int x;
public:
    MyClass(const MyClass& other) : x(other.x) {
        // Copy of the object
    }
};

Move Constructor

Introduced in C++11, it is used to transfer resources from one object to another instead of copying them (to improve performance).

class MyClass {
private:
    int* data;
public:
    MyClass(MyClass&& other) noexcept : data(other.data) {
        other.data = nullptr;
    }
};

Destructors in C++

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

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

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

Syntax

The name of a destructor is the name of the class 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
    }
};

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