Can you explicitly call an implicitly defined operator =( ) ?

  • Follow


Can someone tell me if this is legal or not, in respect of B::operator
=( ) calling the implicitly defined A::operator =( )? I am using this
technique in some C++ that Borland C++ chokes on.

thanks

Kevin
---------------

class A
{
   private:
   int a;
};

class B : public A
{
   private:
   int b;

   public:
   B& operator =( const B& _r_Source )
   {
      if( &_r_Source != this )
      {
         A::operator =( _r_Source );

         b = _r_Source.b;
      }
   }
};


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply kevin_g_frey (24) 3/1/2006 1:21:26 PM

kevin_g_frey@hotmail.com wrote:
> Can someone tell me if this is legal or not, in respect of
> B::operator =( ) calling the implicitly defined A::operator
> =()? I am using this technique in some C++ that Borland C++
> chokes on.

It's fully legal if A is a class type (defined by means of
class, struct or union) -- operator= is a function in every
case, even when it is the compiler which implicitly declares and
defines it.  I'm less sure about things like int::operator=(); I
don't think they are legal.  (Of course, there's never any
reason to do this in normal code, but perhaps some special case
in templates...)

> ---------------

> class A
> {
>    private:
>    int a;
> };

> class B : public A
> {
>    private:
>    int b;

>    public:
>    B& operator =( const B& _r_Source )
>    {
>       if( &_r_Source != this )
>       {
>          A::operator =( _r_Source );

>          b = _r_Source.b;
>       }
>    }
> };

No problem here (except that the test for self assignment isn't
necessary -- and typically, when it is necessary, it's a sign of
a broken operator=).

--
James Kanze                                           GABI Software
Conseils en informatique orient�e objet/
                   Beratung in objektorientierter Datenverarbeitung
9 place S�mard, 78210 St.-Cyr-l'�cole, France, +33 (0)1 30 23 00 34


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply kanze 3/1/2006 4:56:54 PM


kevin_g_f...@hotmail.com wrote
> Can someone tell me if this is legal or not, in respect of B::operator
>  =( ) calling the implicitly defined A::operator =( )?

Yes this is perfectly legal. In fact it compiles very cleanly in
VSNet2003.
Also you can observe that it works correctly as expected.
However I noticed that you have not returned the dereferenced this
pointer.

So your copy assignment operator should have a

return *this ;

at the end .


      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply RenjithMohan 3/1/2006 5:01:02 PM

2 Replies
507 Views

(page loaded in 0.045 seconds)

Similiar Articles:













7/24/2012 12:41:52 PM


Reply: