Page 123 - DCAP404 _Object Oriented Programming
P. 123
Object-oriented Programming
Notes 6.1 Need for Constructor and Destructor
6.1.1 Constructor
Constructor is public method that is called automatically when the object of a particular class is
created. C++ provides a default constructor method to all the classes. This constructor method
takes no parameters. Actually the default constructor method has been defined in system.object
class. Since every class that you create is an extension of system.object class, this method is
inherited by all the classes.
The default constructor method is called automatically at the time of creation of an object and
does nothing more than initializing the data variables of the object to valid initial values.
Notes A Programmer can also define constructor methods for a class if he/she so desires.
While writing a constructor function the following points must be kept in mind:
1. The name of constructor method must be the same as the class name in which it is defined.
2. A constructor method must be a public method.
3. Constructor method does not return any value.
4. A constructor method may or may not have parameters.
Let us examine a few classes for illustration purpose. The class abc as defined below does not
have user defined constructor method.
class abc
{
int x,y;
}
main()
{
abc myabc;
…;
}
The main function above an object named myabc has been created which belongs to abc class
defined above. Since class abc does not have any constructor method, the default constructor
method of C++ will be called which will initialize the member variables as:
myabc.x=0
and
myabc.y=0.
Let us now redefine myabc class and incorporate an explicit constructor method as shown
below:
class abc
116 LOVELY PROFESSIONAL UNIVERSITY