hi
i just read the tutorial on classes on this webpage.. but its unclear to me what the purpose of a constructor and a deconstructor is..could someone elaborate on it please?
thanx in advance,
Boomba,
hi
i just read the tutorial on classes on this webpage.. but its unclear to me what the purpose of a constructor and a deconstructor is..could someone elaborate on it please?
thanx in advance,
Boomba,
Well, the "purpose" is for initialization and de-initialization.
For instance, you may want to initialize member variables or allocate memory off the heap in the constructor. The destructor would perform any neccessary cleanup like releasing allocated resources back to the OS.
The absolute best way to understand them is to play with them. Get comfortable in your understanding of when and whey they are called. Here's a little some'n some'n to show what I mean.
ggCode:#include <iostream> using namespace std; class C { int m_n; public: C() { m_n = 0; cout << "C default constructor" << endl; }//constructor C(int n) : m_n(n) { cout << "C constructor, m_n = " << m_n << endl; }//constructor ~C() { cout << "C destructor, m_n = " << m_n << endl; }//destructor };//C int main() { cout << "Creating c1..." << endl; C c1; cout << "Creating c2(42)" << endl; C c2(42); cout << endl << "returning from main()" << endl << endl; return 0; }//main
I just want to add something.
You should know that they are called implicitly and ofcourse they can be called explicitly.Get comfortable in your understanding of when and whey they are called.
none...
Unless of course you tend to the old C ways, and allocate a raw memory block to a pointer:You should know that they are called implicitly
The constructor won't be called here, and neither would a destructor. Of course, that code is horrible and no-one would ever use it. Just putting in my two cents.Code:class C { public: C() {cout << "C constructor called" << endl; } }; int main() { C *c=(C *)malloc(sizeof(C)); return 0; }
[email protected]
Microsoft Visual Studio .NET 2003 Enterprise Architect
Windows XP Pro
Code Tags
Programming FAQ
Tutorials