Thursday, 26 January 2012

Program Of Constructor With Default Argument In C++

#include<iostream.h>
#include<conio.h>
                     class add       // Declaration of class
{
               private:    // Data Member
int a,b;
public:
add(int x=10,int y=5)
{
a=x;
b=y;
}
           void display( )    //Data member Function
{
int z;
z=a+b;
cout<<"\n sum is="<<z;
}
};
main( )
{
clrscr( );
int p,q;
cout<<"enter number=";
cin>>p>>q;
add a1;(p,q);   // object of class
add a2;
a1.display();
a2.display();
getch();
}
--------------------------------------------------------------------------

Default arguments are formal parameters that are given a value (the default value) to use when the caller does not supply an actual parameter value. Of course, actual parameter values, when given, override the default values.

The syntax and and utility of default arguments is illustrated by the following example based on the Frame class. class Frame { private: ... public: ... void Resize (int width = 100, int height = 150); ... };
In this example, the width and height arguments are both given default values. To see the effect of these default values consider the following use of the Resize method: Frame window (100, 100, 300, 400); ... window.Resize(200, 250); // case 1 window.Resize(200); // case 2 window.Resize(); // case 3
In the first case the window is resized to be 200 X 250: since both parameters are given the default values are ignored. In the second case, the Frame object is resized to be 200 X 150: the default value of 150 is used for the absent second (height) argument while the supplied 200 is used for the first (width) argument. In the third case, the window is resized to be 100 X 200 since both default values are used.


No comments:

Post a Comment