In C++, it is possible to assign
default values to formal arguments of member functions. The following example
makes it clear.
#include<iostream.h>
class A
{
public:
void
show(int=1); // assigning default value
};
void A::show(int p)
{
for(int i=0,;
i<p;i++)
cout<<”Hello”;
}
void main()
{
A A1;
A1.show(); //default
value is taken
A1.show(3); // default value is overridden and 3 is taken
}
It is important to notice that
default values must be specified in the function prototypes and not in function
definitions. Default values can be specified for a formal argument of any type.
Giving default values to arguments of overloaded member functions can lead to
ambiguity errors. The following example makes clear.
class A
{
public:
void show();
void show(int =
0); // it will lead to ambiguity error
}
No comments:
Post a Comment