Jump to content

Draft:Deleted functions (C++)

From Wikipedia, the free encyclopedia

Deleted functions[1] are a feature of the C++ programming language that allow the programmer to prevent specific functions from being called. The most common usage of deleted functions is when the programmer wants to disable copying of a class object.

Deleted functions were added in C++11.

Usage

[edit]

Below is a very simple usage of deleted functions:

void printNum(int x) {
    std::cout << x << '\n';
}

printNum(char) = delete;
printNum(bool) = delete;

The following code forbids the user from having a char or a boolean type as an argument for the printNum function, which are otherwise acceptable due to Integral promotion[2]. If we were to call the function and use a char or a boolean as an argument, we would get a compile error.

Deleted functions are, however, used mostly to disable copying of a class object.

Example(Example const&) = delete;
Example& operator=(Example const&) = delete;

The example above, disables the copy constructor and the copy assignment operator using the delete keyword.

See also

[edit]

References

[edit]
  1. ^ "Function declaration - cppreference.com". en.cppreference.com. Retrieved 2024-11-09.
  2. ^ "Implicit conversions - cppreference.com". en.cppreference.com. Retrieved 2024-11-09.