const references : confusion

From: raj (regmailin_at_yahoo.co.in)
Date: 02/12/04


Date: Thu, 12 Feb 2004 15:40:14 -0600

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::operator=(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::operator=(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?



Relevant Pages

  • Re: Code structurization question ?
    ... If stack space is the only problem, ... int: 1 bytes ... micro controllers, ... typedef struct abc ...
    (microsoft.public.vc.language)
  • Re: structure and malloc
    ... ABC *abc; ... memoryfor structure DEF and its constituting structure ABC. ...
    (comp.lang.c)
  • Re: Cursors in functions
    ... to provide persistance of data beween function calls allowing you to add ... >501 abc 10 ... >> RETURNS int AS ... >> DECLARE @Total int ...
    (microsoft.public.sqlserver.programming)
  • Re: %n !!
    ... i get a strange output. ... int main ... If you're going to call a variadic function such as printf, ... ABC 2 Ok ...
    (comp.lang.c)
  • Re: structure and malloc
    ... ABC *abc; ... DEF *CreateDEF (void) ...
    (comp.lang.c)