Thread: Constructors and Destructors

  1. #1
    Registered User
    Join Date
    Dec 2006
    Posts
    11

    Constructors and Destructors

    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?

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    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).

  3. #3
    Registered User zouyu1983's Avatar
    Join Date
    Nov 2006
    Location
    Fuzhou University, Fujian, China
    Posts
    35
    >> 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^_^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Can a class have multiple destructors?
    By meili100 in forum C++ Programming
    Replies: 1
    Last Post: 05-14-2008, 05:28 PM
  2. Destructors and Constructors on classes
    By Da-Nuka in forum C++ Programming
    Replies: 14
    Last Post: 06-14-2005, 02:08 PM
  3. Constructors and Destructors
    By GravtyKlz in forum C++ Programming
    Replies: 7
    Last Post: 03-09-2003, 10:44 AM
  4. Constructors And Destructors... What's The Point?
    By DeanDemon in forum C++ Programming
    Replies: 7
    Last Post: 12-15-2002, 12:47 PM
  5. Classes: constructors, destructors ???
    By mbeisser21 in forum C++ Programming
    Replies: 18
    Last Post: 07-21-2002, 09:33 PM