Wednesday, December 23, 2009

Why do we need constructors and destructors in object oriented programing?

pls why do we need constructors and destructors in oop and also what are the kinds of constructors that are there. its kinda urgent any help will be highly appreciated thanksWhy do we need constructors and destructors in object oriented programing?
The Constructor in a class is a special block of statements called when an object is created, either when it is declared (statically constructed on the stack, possible in C++ but not in Java and other object-oriented languages) or when it is dynamically constructed on the heap through the keyword ';new';.





In most languages, the constructor can be overloaded in that there can be more than one constructor for a class, each having different parameters. Some languages take consideration of some special types of constructors:





* default constructor - a constructor that can take no arguments


* copy constructor - a constructor that takes one argument of the type of the class.








, the destructor is a method which is automatically invoked when the object is destroyed. Its main purpose is to clean up and to free the resources which were acquired by the object along its life cycle and unlink it from other objects or resources invalidating any references in the process. The use of destructors is key to the concept of Resource Acquisition Is Initialization.Why do we need constructors and destructors in object oriented programing?
Constructors create (allocate memory for ) the object and initializes its fields to default values, unless otherwise specified ...


Kinds of constructors :


1-Default : initializes the fields to the default values specified by the programming language


2-Parametrized ( takes parameter to set the values to those given parameters )


3-Static ( in some languages ): initializes static fields


4-Copy constructor : Creates a copy of the object





Destructors release the memory used for the object .

No comments:

Post a Comment