COMPUTER SCIENCE CONSTRUCTORS AND DESTRUCTORS

There are three types of constructors

a) Non-parameterized or Default Constructor
b) Parameterized Constructor
c) Copy Constructors

a) Default constructor: A constructor that accepts no parameter is called the default constructor. With a default constructor, objects are created just the same way as variables of other data types are created.

class X
{
int i ;
public:
int j, k ;
------
//Members Functions
------
};

Eg: X ob1;
Student s1;

If a class has no explicit constructor defined,the compiler will supply a default constructor. This implicitly declared default constructor is an inline public members of its class. Declaring a constructor with arguments hides the default constructor.There can be a default constructor as well as another constructor with arguments for a class, having multiple constructors is called as constructor overloading. A constructor can also have default arguments. A constructor with default arguments is equivalent to a default constructor.

Eg:

class Rectangle
{
float l,b,a;
public:
Rectangle ( float len = 5.0, float bre = 5.0)
//Constructor with Default arguments
{
l = len;
b = bre;
}
-----
-----
};
void main( )
{
Rectangle first(7.0,9.5);
Rectangle second;
//Takes default argument values. Equivalent to second(5.0,5.0)
----
----
}

The default constructors are very useful when you want to create objectswithout having to type the initial objects every time with pre specified initial values or if you want to create array of objects of your class type. You can’t create an array of objects unless your class has a default constructor (implicitly or explicitly defined).

b) Parameterized Constructor: A constructor that take arguments, iscalled as parameterized constructor. The parameterized constructor allow us toinitialize the various data elements of different objects with different values when they are created. This is achieved by passing different values as arguments to the constructor function when the objects are created.

Eg:

class Rectangle
{ float l,b,a;
public:
Rectangle ( float len , float bre )
//Parameterized Constructor.
{ l = len;
b = bre;
}
-----
-----
};
void main( )
{
Rectangle first(7.0,9.5);
----
----
}

With a parameterized constructor, the initial values must be passed at the time of object created. This can be done in two manners:

(i) By calling the constructor implicitly(implicit call) Eg: Rectangle first(8.5,3.9);
(ii) By calling the construct or explicitly(Explicit call)

Eg: Rectangle first = Rectangle (8.5,3.9);


CBSE Computer Science Solved Revision Tour By Mr. Ravi Kiran ( [email protected] )