In c++ what does a tilde "~" before a function name signify?

C++

C++ Problem Overview


 template <class T>
 class Stack
 {
 public:
 	Stack(int = 10) ; 
 	~Stack() { delete [] stackPtr ; }  //<--- What does the "~" signify?
 	int push(const T&); 
 	int pop(T&) ;  
 	int isEmpty()const { return top == -1 ; } 
 	int isFull() const { return top == size - 1 ; } 
 private:
 	int size ;  
 	int top ;  
 	T* stackPtr ;  
 } ;

C++ Solutions


Solution 1 - C++

It's the destructor, it destroys the instance, frees up memory, etc. etc.

Here's a description from ibm.com:

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

See https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/rzarg/cplr380.htm

Solution 2 - C++

As others have noted, in the instance you are asking about it is the destructor for class Stack.

But taking your question exactly as it appears in the title:

> In c++ what does a tilde “~” before a function name signify?

there is another situation. In any context except immediately before the name of a class (which is the destructor context), ~ is the one's complement (or bitwise not) operator. To be sure it does not come up very often, but you can imagine a case like

if (~getMask()) { ...

which looks similar, but has a very different meaning.

Solution 3 - C++

It's a destructor. The function is guaranteed to be called when the object goes out of scope.

Solution 4 - C++

This is a destructor. It's called when the object is destroyed (out of life scope or deleted).

To be clear, you have to use ~NameOfTheClass like for the constructor, other names are invalid.

Solution 5 - C++

It's the destructor. This method is called when the instance of your class is destroyed:

Stack<int> *stack= new Stack<int>;
//do something
delete stack; //<- destructor is called here;

Solution 6 - C++

That would be the destructor(freeing up any dynamic memory)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMonte HurdView Question on Stackoverflow
Solution 1 - C++inanutshellusView Answer on Stackoverflow
Solution 2 - C++dmckee --- ex-moderator kittenView Answer on Stackoverflow
Solution 3 - C++Samuel DanielsonView Answer on Stackoverflow
Solution 4 - C++KlaimView Answer on Stackoverflow
Solution 5 - C++PierreView Answer on Stackoverflow
Solution 6 - C++maxfridbeView Answer on Stackoverflow