Search

Deleting functions in C++

Avoiding unnecessary overloads


Deleting functions in C++


In C++, the delete keyword is used in two different situations, depending on the context:

1. delete operator can be used to free dynamically allocated memory:

When you dynamically allocate memory using new, you need to free that memory when you no longer need it to avoid memory leaks. The delete operator is used to free dynamically allocated memory. On the other hand, for automatic use, you can (and should always use) smart pointers.

2. delete operator for functions:

When you declare a function using delete, you are declaring that this function is deleted and cannot be used. This is useful for classes with member functions that you want to prevent from being called or inherited.


Example of how to delete functions in C++

Suppose you have this function below: print_num(int) which takes the primitive type int as a parameter:

void print_num(int num){
   std::cout << num << '\n';
}

When calling this function, note that we can pass the types: char, bool and float/double that it will receive normally:

void print_num(int num){
   std::cout << num << '\n';
}

int main(){
   print_num(9);
   print_num('a');
   print_num(true);
   print_num(3.6);
}

When compiling, note that it will work normally:

g++ main.cpp
./a.out
9
97
1
3

To avoid this overhead we use the delete statement to nullify some types:

void print_num(char) = delete;

In this case, the types char and float/double will already receive an error when compiling:

void print_num(char) = delete;  Call to deleted function 'print_num'

Remembering that float/double will already receive a warning(if you are using an LSP), but it will compile normally!

We can also use the bool type to not overload:

void print_num(bool) = delete;

Therefore, in order to compile our code, we will need to comment the lines referring to the code above, leaving the following at the end:

#include <iostream>

void print_num(int num){
   std::cout << num << '\n';
}

void print_num(char) = delete;
void print_num(bool) = delete;

int main(){
   print_num(9);
   //print_num('a'); ■ Call to deleted function 'print_num'
   //print_num(true); ■ Call to deleted function 'print_num'
   //print_num(3.6); ■ Call to 'print_num' is ambiguous
   return 0;
}

Remembering that you can still optimize your code using template, making it like a boss!:

#include <iostream>

void print_num(int num){
   std::cout << num << '\n';
}

template<typename T>
void print_num(T) = delete;

int main(){
   print_num(9);
   //print_num('a'); ■ Call to deleted function 'print_num'
   //print_num(true); ■ Call to deleted function 'print_num'
   //print_num(3.6); ■ Call to 'print_num' is ambiguous
   return 0;
}

In summary, within this context, Deleting functions in C++:

delete = “I prohibit this” or “This does not exist

For more information access here.


cpp


Share



Comments