2

Possible Duplicate:
In c++ what does a tilde “~” before a function name signify?

What is the difference between the line with the ~ and the other line?

public:    
       myClass() {};    
       ~myClass() {};
Community
  • 1
  • 1
Crash_Override
  • 368
  • 1
  • 3
  • 20

2 Answers2

7

myClass(){} is called constructor and ~myClass(){} is called destructor!

Constructor is invoked when an object is created, and destructor is invoked when an object is destroyed.

myClass *pObj = new myClass(); //constructor is invoked;
//work with pObj;

delete pObj; //destructor is invoked;

That is an example when you use new and delete. new causes constructor to be invoked, and delete causes destructor to be invoked.

Lets see another example:

{
    myClass Obj; //constructor is automatically invoked;
  //work with Obj;


} //<--here Obj goes out of scope which causes destructor to be automatically invoked;

With an automatic object, constructor is automatically invoked, and when the object goes out of scope, the destructor is automatically invoked.

Nawaz
  • 353,942
  • 115
  • 666
  • 851
0

The function "myClass" is a constructor and is invoked when an object of that type is created. A class can provide multiple different constructors that can be used to create (i.e. construct) objects of that type.

The function "~myClass" is a destructor and is invoked when an object of that type is destroyed (which occurs when an automatic storage-allocated instance goes out of scope or when a pointer to a dynamically allocated instance of that type has been deleted using the delete operator). Whereas a class can provide multiple constructors, a class can only provide a single destructor.

When a class has virtual methods, the destructor should also be marked virtual.

Michael Aaron Safyan
  • 93,612
  • 16
  • 138
  • 200