Module lessons (2/2)
Constructors and Destructors
Constructors and destructors are special member functions that manage the lifecycle of objects: their creation (initialization) and their destruction (resource cleanup).
Constructors
A constructor is called automatically when an object of the class is created in memory.
- It has the same name as the class.
- It does not have a return type (not even
void). - It can be overloaded to accept different sets of parameters.
#include <iostream>
#include <string>
class Item {
private:
std::string name;
double price;
public:
// Parameterized constructor
Item(std::string itemName, double itemPrice) {
name = itemName;
price = itemPrice;
std::cout << "Object " << name << " created." << std::endl;
}
void display() {
std::cout << name << ": " << price << " EUR" << std::endl;
}
};
int main() {
// Implicit call to the constructor passing parameters
Item book("Libro C++", 29.99);
book.display();
return 0;
}
Default Constructor
If you do not define any constructor, the C++ compiler generates a default constructor without parameters. However, if you write a custom constructor with parameters, the compiler no longer generates the default one automatically, so you will need to define it explicitly if needed:
class Point {
public:
int x;
int y;
// Explicit default constructor
Point() {
x = 0;
y = 0;
}
};
Destructors
A destructor is called automatically when the object goes out of scope or is explicitly removed from memory.
- It has the same name as the class preceded by a tilde
~(e.g.~Item()). - It does not accept parameters and has no return type.
- It is used to release resources (e.g., closing files, freeing dynamically allocated memory).
class ResourceManager {
public:
~ResourceManager() {
// Cleanup code
std::cout << "Resources released." << std::endl;
}
};
Try it yourself
Define a class named User with a private member std::string username. Add a public constructor that accepts a string (User(std::string name)) and uses it to initialize username. Add a public getter std::string getUsername() that returns username. In main, create a User object passing 'Alice' as name, and print its username using std::cout.
Show hint
Il costruttore ha lo stesso nome della classe e non specifica alcun tipo di ritorno, nemmeno `void`.
Solution available after 3 attempts
Define a class named Point with two public integer members: x and y. Add a default constructor (no parameters) that initializes x and y to 0. In main, create a Point object using the default constructor and print x and y.
Show hint
Il costruttore di default non prende argomenti: `Point() { x = 0; y = 0; }`.
Solution available after 3 attempts