Saturday, May 22, 2010

May i know what is the use of constructor function in c++?

Constructors are methods that are called when an object is instantiated. You can think of them almost like autoboot programs.





Remember that classes may have attributes within them, which may in fact be other sets of class objects, which will need to be constructed as well.





In addition to setting attribute values, constructors can be used to perform other functionality, such as establish a socket connection from within the class.





They are very useful, since you always know they will be invoked. If you don't code one, the compiler will supply a default one for you.





If you provide your won constructor, you at least need to think about a destructor. Just as the constructor is always called when the object is instantiated, the destructor is always called when the object goes out of scope or is deleted.





The destructor is useful for clean up. Consider the constructor that does a "new" for an attribute. The destructor should delete that attribute when done to free up the memory.

May i know what is the use of constructor function in c++?
A constructure function can be used to initialize the object being created.





Look at following code:





class x {


private: int y;


public: put_y(int a) { y=a; };


get_y(void) { return y; }


};





Then you create an object like:


x obj1;


this obj1 object doesnt have any values for y. if you have a constructor then "y" can get an initial value. Look for revised code:





class x {


private: int y;


public: x() { y=10; } // constructor has same name as class name


put_y(int a) { y=a; };


get_y(void) { return y; }


};





Constructors can be overloaded to do different operations depending on what is passed to them.





Best example to understand a Constructor is: When you open Micosoft Excel, It automatically comes with a blank worksheet. Such automatic tasks constructor can do.





Hope this helps.
Reply:It creates the object. Allows you to assign values to primitives or do anything else you want to do when constructing the object, or bringing it into existence. For example in a constructor for a class called Point, I could assign values to perhaps private x and y variables in my class.


Point::Point(int a, int b){


m_x=a;


m_y=b;


}


No comments:

Post a Comment