constructor WHY?

This is a discussion on constructor WHY? within the C++ Programming forums, part of the General Programming Boards category; ok guys a constructor is a special type of member function its automatically called when you create a object, point ...

  1. #1
    Unregistered
    Guest

    constructor WHY?

    ok guys a constructor is a special type of member function its automatically called when you create a object, point object(2,5);

    but why do we need them when member functions can be passed arguments and assign these arguments to parameters
    oh sorry think i've just got it passing arguments will innitialize identifiers but it will not create an object, is this why? and any other reasons.

    thanks.

  2. #2
    &TH of undefined behavior Fordy's Avatar
    Join Date
    Aug 2001
    Posts
    5,786
    A constructor is a good place to initalise and allocate memory for the member variables.

    For example. Your class holds a dynamically allocated char array. You have a member function to print it, and one to reverse it and one to sort it. If you did not initialise and allocate space before using any of these functions, you are stuffed, but if you put in a constructor (as it will be called first) to set the pointer and allocate a little memory and set it to say " ", you can avoid errors to some extent.

  3. #3
    Registered User
    Join Date
    Aug 2001
    Posts
    223

    constructors why

    To reinfor the last reply...

    the constructor allows the object to be initialized in a stable condition.

    For instance and object of the type SSN could have the value

    000-00-0000 stored at construction time, instead of garbage like &#@$(*&#|||||
    zMan

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21