Constructors......cont

Parameterized Constructors

A default constructor initilizes the data mambers of all objects with the same set of values. However, in practice, it may be necessary to initialize the various data elements of different objects with different values when they are created. Often you will allow users of your classes to pass arguments to the constructor. This can be achieved by passing arguments to constructor functions when the objects are created. Constructors that can take arguments are called Parameterized Constructors

For example, the default constructor number() may be modified as given below:

class number

{

int a, b;

public;

number(int x, int y); //parameterized constructor

-----

-----

};

number::number(int x, int y); //parameterized constructor defined

{

a=x;

b=y;

}

Passing Initial Values as Arguments

When a constructor has been parameterized, the object declaration statment such as

member ob1;

may not work. We must pass the initial values as arguments to the constructor function parameterized when an object is declared. This can be done in two ways:

1. By calling the constructor implicitly:

number ob1(0,100);

2. By calling the constructor explicitly:

number ob1=number(0,100);

The implicit method is known as the shorthand method. It is used very often as it is shorter, looks better and is easy to implement.

Copy Constructor

A copy constructor is a specail constructor that can be called to copy an object. It is used to declare and initialize one object from another object.

For example:

number ob2(obi);

would define the object ob2 and at ath same time initialize it to the values of ob1.

another form of this statment is :

number ob2=ob1;

The process of initializing through a copy constructor is known as copy initialization.

HOME LEARN C++ PREVIOUS NEXT