R
raj
I need explanation of the behavior of the following code. When run as it is, it gives error.
//-------------------------<start>------------------
#include <iostream.h>
#include <stdlib.h>
class ABC
{
private: int x;
public:
ABC() { x=0; }
ABC (int a) { x=a; }
ABC (const ABC& abc)
{
x=abc.x+1; //increasin by 1 just as a token of copy constructor invocation
cout<<"\n\tCopy constructor invoked.";
}
ABC& operator=(ABC& abc) //NO ERROR IF CHANGED TO : ABC& operator=(const ABC& abc)
{ //line 18
x=abc.x;
return (*this);
}
ABC friend frnd_func();
};
ABC frnd_func()
{
ABC abc(100);
return abc;
}
int main()
{
ABC a1(5);
ABC a2=a1; //just to test copy constructor.
a2=frnd_func(); //gives error : "initialisation of non-const reference type 'cxlass ABC&'
// from rvalue of typpe 'ABC' in passing argument 1 of 'ABC:perator=(ABC&)'
cout<<"\n\n";system("PAUSE");
return 0;
}
//-------------------------<end>---------------------
Running it in Bloodshed Dev C++ gives the following error:
35: Initialisation of non-const reference type 'class ABC&'
35: from rvalue of type 'ABC'
18: in assigning argument 1 of 'ABC:perator=(ABC &)'
But, if I change the = overloading declaration to:
ABC& operator=(const ABC& abc)
then the error vanishes.
Why should i need to add the 'const' keyword here?
//-------------------------<start>------------------
#include <iostream.h>
#include <stdlib.h>
class ABC
{
private: int x;
public:
ABC() { x=0; }
ABC (int a) { x=a; }
ABC (const ABC& abc)
{
x=abc.x+1; //increasin by 1 just as a token of copy constructor invocation
cout<<"\n\tCopy constructor invoked.";
}
ABC& operator=(ABC& abc) //NO ERROR IF CHANGED TO : ABC& operator=(const ABC& abc)
{ //line 18
x=abc.x;
return (*this);
}
ABC friend frnd_func();
};
ABC frnd_func()
{
ABC abc(100);
return abc;
}
int main()
{
ABC a1(5);
ABC a2=a1; //just to test copy constructor.
a2=frnd_func(); //gives error : "initialisation of non-const reference type 'cxlass ABC&'
// from rvalue of typpe 'ABC' in passing argument 1 of 'ABC:perator=(ABC&)'
cout<<"\n\n";system("PAUSE");
return 0;
}
//-------------------------<end>---------------------
Running it in Bloodshed Dev C++ gives the following error:
35: Initialisation of non-const reference type 'class ABC&'
35: from rvalue of type 'ABC'
18: in assigning argument 1 of 'ABC:perator=(ABC &)'
But, if I change the = overloading declaration to:
ABC& operator=(const ABC& abc)
then the error vanishes.
Why should i need to add the 'const' keyword here?