Constructors are special class functions which performs initialization of every object. The Compiler calls the Constructor whenever an object is created. Constructors initialize values to object members after storage is allocated to the object. Whereas, Destructor on the other hand is used to destroy the class object.
A destructor is a member function that is invoked automatically when the object goes out of scope or is explicitly destroyed by a call to delete . A destructor has the same name as the class, preceded by a tilde ( ~ ). For example, the destructor for class String is declared: ~String() .
No. You never need to explicitly call a destructor (except with placement new ). A class's destructor (whether or not you explicitly define one) automagically invokes the destructors for member objects. They are destroyed in the reverse order they appear within the declaration for the class.
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.
In the class declaration (probably in a header file) you need to have something that looks like:
class StackInt {
public:
StackInt();
~StackInt();
}
To let the compiler know you don't want the default compiler-generated versions (since you're providing them).
There will probably be more to the declaration than that, but you'll need at least those - and this will get you started.
You can see this by using the very simple:
class X {
public: X(); // <- remove this.
};
X::X() {};
int main (void) { X x ; return 0; }
Compile that and it works. Then remove the line with the comment marker and compile again. You'll see your problems appear then:
class X {};
X::X() {};
int main (void) { X x ; return 0; }
qq.cpp:2: error: definition of implicitly-declared `X::X()'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With