1. How does the compiler interpret more than one definitions having same name? What steps does it follow to distinguish these?
Ans.
The compiler will follow the following steps to interpret more than one definitions having same name: (i) if the signatures of subsequent functions match the previous function’s, then the second is treated as a redeclaration of the first. (ii) if the signature of the two functions match exactly but the return type differ, the second declaration is treated as an erroneous re-declaration of the first and is flagged at compile time as an error. (iii) if the signature of the two functions differ in either the number or type of their arguments, the two functions are considered to be overloaded.
2. Discuss the benefits of constructor overloading. Can other member function of a class be also overloaded? Can a destructor be overloaded? What is your opinion?
Ans.
Constructor overloading are used to increase the flexibility of a class by having more number of constructors for a single class. By this we can initialize objects more than one way. Yes, Other member function of a class can also be overloaded. A destructor cannot be overloaded.
3. Write the output of the following C++ code. Also, write the name of feature of Object Oriented Programming used
in the following program jointly illustrated by the functions [I] to [IV]:
#include<iostream.h>
void Line() //Fuction [I]
{ for(int L=1;L<=80;L++) cout<<"-";
cout<<endl;
}
void Line(int N) //Fuction [II]
{ for(int L=1;L<=N;L++) cout<<"*";
cout<<endl;
}
void Line(char C,A,int N) //Fuction [III]
{ for(int L=1;L<=N;L++) cout<<C;
cout<<endl;
}
void Line(int M,int N) //Fuction [IV]
{ for(int L=1;L<=N;L++) cout<<M*L;
cout<<endl;
}
void main()
{
int A=9,B=4,C=3;
char K='#';
Line(K,B);
Line(A,C);
}
Ans.
Output: # # # # 9 18 27
The name of feature of Object Oriented Programming used in the above program jointly illustrated by the functions [I] to [IV] is known as ‘function overloading’.
4. Write definitions for two versions of an overloaded function. This function’s 1st version sum() takes an argument, int array, and returns the sum of all the elements of the passed array. The 2nd version of sum() takes two arguments, an int array and a character (‘E’ or ‘O’). If the passed character is ‘E’, it returns the sum of even elements of the passed array and is the passed character is ‘O’, it returns the sum of odd elements. In case of any other character, it returns 0 (zero).
Ans:
int sum(int a[])
{
int n,sum=0;
cout<<"Enter n:";
cin>>n;
for(int i=0;i<n;i++)
{
sum=sum+a[i];
}
return sum;
}
//
int sum(int a[],char c)
{
int even=0,odd=0;
switch(c)
{
case 'E':
for(int i=0;i<5;i++)
{
if(a[i]%2==0)
{
even=even+a[i];
}
}
return even;
case 'O':
for(int j=0;j<5;j++)
{
if(a[j]%2!=0)
{
odd=odd+a[j];
}
}
return odd;
}
}
0 comments:
Post a Comment
Thanks for leaving a comment. As soon as it's approved, it will appear.