Parametrized Constructors Assignment Help

Assignment Help: >> Union, Nested Classes, Constructors and Destructors - Parametrized Constructors

Parameterized Constructors

Constructors could be invoked within arguments, only as in the case of functions.  The argument list can be specified inside braces same to the argument-list in the function.  Constructors within arguments are known as parameterized constructors. The distinguishing features are that the name of the constructor functions has to be the similar as that of its class name. Other constructor along with arguments could have been provided within one integer value to initialize the data members.

Example

class test

{

//data

test(int data1) // constructor with parameter

{

//data

}

-----------

};

test t1(2);        // 2 is passed a parameter

test t2 = 3;      // 3 is passed as a parameter

Because C++ language permits function overloading, a constructor arguments could co-exist along with another constructor without arguments.

// sample program

# include<iostream.h>

const int MAX_ITEMS = 25;

class bag

{

private:

int contents[MAX_ITEMS];

int itemcount;

public:

bag ( )

{

itemcount = 0;

}

bag (int item )

{

contents[0] = item;

itemcount = 1;

}

void put(int item)

{

contents[itemcount++] = item;

}

void show ( );

};

void bag :: show ( )

{

if (itemcount)

for(int i = 0; i<itemcount ; i++)

cout<< contents[I] << " ";

else

}

cout<<"Nil";

cout << endl;

void main( )

int item;

bag b1;

bag :: bag ( )

bag b2 = 4;

bag :: bag( int item)

cout<< "gifted bag1 initally has :";

b1.show ( );

cout<<"gifted bag2 initially has :";

b2.show ( );

while (1)

{

cout<<"enter the  item number to be put into the bag <0-no item>";

cin>> item;

if (item == 0) break; b2.put(item);

cout<<"items in bag 2:";

b2.show ( ):

}

}

The output is

gifted bag1 initally has : Nil

gifted bag2 inially has: 4

enter the item number to be put into the bag2<0-no item> 1

items in bag2 : 4 1

enter the item number to be put into the bag 2<0-no item> 5

items in bag2 4 1 5

The bag class has two constructors. The 1st constructor does not have arguments. The next constructor has a single argument

The statement bag b1;

creates the object b1 of class bag and initializes its data member through invoking the no-argument constructor bag :: bag ( )

Free Assignment Quote

Assured A++ Grade

Get guaranteed satisfaction & time on delivery in every assignment order you paid with us! We ensure premium quality solution document along with free turntin report!

All rights reserved! Copyrights ©2019-2020 ExpertsMind IT Educational Pvt Ltd