***Welcome to ashrafedu.blogspot.com * * * This website is maintained by ASHRAF***

Monday, June 14, 2021

CONSTRUCTORS WITH DEFAULT ARGUMENTS

 Like normal functions, constructors can also be defined with default arguments.

When an object of a class is created, the C++ calls the suitable constructor for initializing that object.

The default arguments are specified in the definition of a constructor.

Syntax:-

public:

Classname( datatype var=value, datatype var=value, …)

{

--------

Statements;

}

Example. //Demonstration of constructor with default arguments

#include<iostream.h>

#include<conio.h>

class sample

{

private:

int a,b;

public:

sample()

{ a=b=0; }

sample(int x,int y=0)

{

a=x;

b=y;

}

void show()

{ cout<<"\n a= "<<a<<"\t b= "<<b;

}

};

void main()

{

clrscr();

sample s(10);

s.show();

getch();

}

In the above example constructor sample s(10) is called with only one parameter. According to program sample may take no arguments or two arguments. Here comes the default argument to give value to second argument in sample s(10) which will be sample s(10,0) as default value of second parameter y=0. 

No comments:

Post a Comment