// Function overloading concepts rules are also applicable to Constructor as it is also a function with the same name to its //class
#include<iostream>
using namespace std;
class Complex
{
int real;
int img;
public:
Complex(int r=0, int i=0) // parameterized Constructor with default parameters
{
real=r;
img=i;
}
Complex() // Compiler generates ambiguity error as both parameters have default value in parameterized constructor
{
real=0;
img=0;
}
void putdata()
{
cout<<real<<"+ "<<img<<"i"<<endl;
}
};
int main()
{
Complex c1,c2(10),c3(10,20); //Ambiguity error
c1.putdata();
c2.putdata();
c3.putdata();
}
Note: Compiler only generates ambiguity error if and only if we create an object with no parameters i.e. if the statements in main function is as follows;
Complex c2(10),c3(10,20); //OK, no error as there is no any object with default arguments that leads to ambiguity;
c2.putdata();
c3.putdata();
then there will be no any errors in the code as function overloading is compiled time binding and always tries to bind the function call with definition during the compilatoin process.
#include<iostream>
using namespace std;
class Complex
{
int real;
int img;
public:
Complex(int r=0, int i=0) // parameterized Constructor with default parameters
{
real=r;
img=i;
}
Complex() // Compiler generates ambiguity error as both parameters have default value in parameterized constructor
{
real=0;
img=0;
}
void putdata()
{
cout<<real<<"+ "<<img<<"i"<<endl;
}
};
int main()
{
Complex c1,c2(10),c3(10,20); //Ambiguity error
c1.putdata();
c2.putdata();
c3.putdata();
}
Note: Compiler only generates ambiguity error if and only if we create an object with no parameters i.e. if the statements in main function is as follows;
Complex c2(10),c3(10,20); //OK, no error as there is no any object with default arguments that leads to ambiguity;
c2.putdata();
c3.putdata();
then there will be no any errors in the code as function overloading is compiled time binding and always tries to bind the function call with definition during the compilatoin process.
No comments:
Post a Comment