Chapter 8 Function Overloading and Member Functions
Chapter 8 Function Overloading and Member Functions
function.
ame.membername.
violates the rule of encapsulation and data hiding.
5. Write the syntax of a friend function. (U)
ANS:
class className
{
public:
friend returnType functionName ( arguments);
};
ANS:
The inline function definition is too long or too complicated.
The inline function is recursive.
2. What is function overloading? Write the need for function overloading. (U)
3. What is function overloading? Explain with a programming example. (U)
ANS:
Function Overloading means multiple functions have same name, but differ in the number of
arguments or data types of arguments.
4. Explain with a programming example to overload a function with different number of arguments.
(U)
ANS:
class overload
{
public:
int area ( int l, int b) // area of rectangle
{
return (l * b);
}
float area ( float r) // area of circle
{
return (3.14 * r * r);
}
float area (float b, float h) // area of triangle
{
return (0.5 * b * a);
}
};
void main( )
{
overload f;
clrscr( );
cout<<” Area of Rectangle:”<<f.area(4,6)<<endl; // area of rectangle
cout<<”Area of Circle:”<<f.area(10)<<end; // area of circle
cout<<”Area of Triangle:”<<f.area(3.0, 7.0)<<endl; // area of triangle
getch();
}
OUTPUT:
Area of Rectangle: 24
Area of Circle: 314.2857
Area of Triangle: 10.5
5. Explain with a programming example to overload a function with different data type of
arguments.(U)
ANS:
int product ( int p, int q, int r);
float product ( float x, float y,float z);
int product ( int p, int q, int r) // Integer
{
cout<<”Product = “<<p * q * r << endl;
}
float product ( float x, float y, float z) // Float
{
cout<< “Product = “ << x * y*z <<endl;
}
……….. ;
return expression ;
}
OUTPUT:
Enter the input number 4
Cube of 4 = 64
8. What is a friend function? What are the characteristics of a friend function? (U)
ANS: A friend function is a non-member function of a class has the access permission to the
private member of the class.
The friend functions have the following properties:
o private and
protected members of the class.
function.
keyword friend. But while defining friend function it does not use
either keyword friend or : : operator.
n object
name.membername.
Example:
class modulas
{
private:
int a;
public:
void readdata( )
{
cout<<”Enter the Number”<<endl;
cin>>a;
}
friend int even(modulas);
};
Int even(modulas n)
{
if(n.a % 2 = = 0) //friend function can access the private data a of the object n
return 1;
else
return 0;
}