In C++, you can use the delete
keyword to prevent specific constructor calls, ensuring that certain conversions or initializations are not allowed.
This is particularly useful for preventing conversions that don’t make logical sense or could introduce bugs.
For example, let’s prevent a Vector
class from being constructed using a bool
:
#include <iostream>
class Vector {
public:
float x, y, z;
// Constructor from float is allowed
explicit Vector(float value)
: x(value), y(value), z(value) {}
// Constructor from bool is deleted
Vector(bool) = delete;
};
void Move(Vector direction) {
std::cout << "Moving in direction: "
<< direction.x << ", "
<< direction.y << ", "
<< direction.z << "\n";
}
int main() {
Vector v1(1.0f);
// Moving in direction: 1, 1, 1
Move(v1);
// Error: constructor is deleted
Vector v2(true);
// Error: constructor is deleted
Move(true);
}
error: attempting to reference a deleted function
note: 'Vector::Vector(bool)': function was explicitly deleted
delete
keyword to specify which constructor you want to disable.Vector
class has three float members: x
, y
, and z
.float
is explicitly defined and allowed.bool
is marked with = delete
. This prevents any code from using this constructor, ensuring that a Vector
cannot be created with a bool
.In the main()
function, creating a Vector
with a float
works as expected. However, attempting to create a Vector
with a bool
results in a compilation error.
delete
By using delete
, you can fine-tune the behavior of your classes, ensuring that they are used correctly and safely. This technique is particularly valuable in large codebases where unintended conversions can lead to subtle and hard-to-find bugs.
Answers to questions are automatically generated and may not have been reviewed.
Learn how to add conversion functions to our classes, so our custom objects can be converted to other types.