Hi,
Can anybody tell me what Constructors and Destructors really are for? I've written some code for my class without them and it worked really fine. When should I use them and why?
Hi,
Can anybody tell me what Constructors and Destructors really are for? I've written some code for my class without them and it worked really fine. When should I use them and why?
Constructors are for initializing the data in your class. Even for beginning level classes they are usually important because otherwise your data will not be initialized to a good value. For example, if you have an int or double member variable in your class and don't initialize it to some good value, if somebody tries to call a function that uses that value they will get strange results.
The destructor cleans up anything that you want cleaned up when an instance of your class is destroyed. Beginner classes don't usually need to clean up anything in the destructor because the type of resources that need to be cleaned up are generally from more advanced concepts. If and when you start using new/delete in your classes, you will probably be calling delete in the destructor to free the memory and destroy the object you allocated.
>> it worked really fine.
Be careful about using this as a test. Often, incorrect code works fine in one situation when you are testing it, but later fails (like when your customer or teacher tries it).
>> I've written some code for my class without them and it worked really fine
The compiler will create a default constructor for you if you don't creat any,but the constructor that the compiler created usually works beyond your intention.
Hello, guys, i come from china, so i am not good at english. If you find the sentence i wrote full of mistakes, please tell me.
I confirm that my english and programming skills will be improved with your help in this forum. thanks^_^