Thread: class destructors/constructors?

  1. #1
    Programming is fun, mkay?
    Join Date
    Oct 2001
    Posts
    490

    Question class destructors/constructors?

    I have a C/C++ book. I am doing windows programming along with console. I just had a question. What are class constructors and destructors for. I saw this example before:


    class Cat
    {
    public:
    Cat(int initialAge); // Constructor
    ~Cat(); // Destructor

    int getage();
    void SetAge(int age);

    private:
    int itsage;
    };

    // Sets up functions in class "Cat"
    ... // Some Code

    int main()
    {
    Cat Frisky(5);

    Frisky.Meow();

    ... // More code
    }


    What are they used for?
    Website(s): http://www16.brinkster.com/trifaze/

    E-mail: [email protected]

    ---------------------------------
    C++ Environment: MSVC++ 6.0; Dev-C++ 4.0/4.1
    DirectX Version: 9.0b
    DX SDK: DirectX 8.1 SDK

  2. #2
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    Cat Frisky(5);


    Well that right there shows you what a constructor does... Frisky is an object of the class Cat. When you 'instantiate' the object you can set the initial age.

    You can have as many constructors as you want to that can have different input types. (overloading) There is no return on a constructor and it is named the same as the class.

    Not much more to it than that.

    Destructors... as the name implies... destroys your object. They are used to do things like clean up memory (delete) and other things.

    There is a default constructor and destructor for your class that is put in there by your compiler. So if you do not include one (bad practice), one of each will be created for you. (Though it will not do anything really).

    Make any sense?
    Blue

  3. #3
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    In a basic sense constructors make objects and destructors destroy them. The idea behind constructors is that it eliminates the possibility of having uninitialised data. Another use for constructors is to allocate dynamic memory. This dynamic memory would then normally be freed in the destructor eliminating memory leaks.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Class design problem
    By h3ro in forum C++ Programming
    Replies: 10
    Last Post: 12-19-2008, 09:10 AM
  2. Two conceptual questions
    By AntiScience in forum C++ Programming
    Replies: 3
    Last Post: 11-01-2007, 11:36 AM
  3. Defining derivated class problem
    By mikahell in forum C++ Programming
    Replies: 9
    Last Post: 08-22-2007, 02:46 PM
  4. matrix class
    By shuo in forum C++ Programming
    Replies: 2
    Last Post: 07-13-2007, 01:03 AM