On 2008-04-18 23:00, Jeff Baker wrote:
> How does an assignment operator work? Following the code that I give
below,
> I notice it isn't clear how the base operator works. I am not sure. It
seems
> to me that there is a copy constructor formed that is used after the '='
is
> call. Cout <<
> "assigment operator ", prints first the at the return the copy
constuctor is
> called. Is there a copy constructor created before the print statement
is
> executed or is it during the return a.s? Or what is going on?
>
> Here is the code:
>
> #ifndef H_H
> #define H_H
> # include <iostream>
> using namespace std;
> class base
> {
> private:
> char s;
> public:
> base( ){}
> base(const char a ):s(a) {cout << "construction with arg " << int(a)
<<
> endl;}
> base(const base & a){cout <<"copy constructor " << int(a.s) <<
endl;}
> base operator=(const base & a){cout << "assignment operator " <<
a.s <<
> endl; return a.s;}
> ~base( ) {cout << "destruction" << endl;}
> };
> #endif
> #include "h.h"
> int main()
> {
> base b3;
> base b1 = 'x'; // is equivalent to base b1('x');
> base b2 = b1; //copy constructor is called Is seen as Base b2(b1)
> b3 = b1; // assignment operator called and copy constructor is called
>
> return 0;
> }
When I run this I get "construction with arg 120" as the last message
before the destructors. The reason can be found in the return-type of
the assignment operator, it returns an object of type base, which is
constructed using the constructor taking a char.
Your assignment operator should probably return a reference to itself:
base& operator=(const base & a)
{
cout << "assignment operator " << a.s << endl; return *this;
}
BTW:
Don't put "using namespace" in header-files, all files including the
header will be affected.
--
Erik Wikström
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|