Topic: constant constructor - why not


Author: guest@igpm.rwth-aachen.de (Helmut Jarausch)
Date: 2 Mar 1994 08:49:58 GMT
Raw View
Dear experts,
I wonder why C++ does not allow for constant constructors, since it might
be very useful for a constructor to know that it is constructing a constant
object. Just as a simple example

class STR
{ char *text;
  int  length;
 public:
  STR( const STR& Source );
    // get space for a copy and copy text
  STR( const STR& Source ) const { text= Source.text; length= Source.length; }
};

Or is there an alternate  mechanism to save copying in a "copy constructor"
for a constant object.
Thank you for your comments,

Helmut Jarausch
Institute of Technology
RWTH Aachen
Germany





Author: crd@netcom.com (Craig Dickson)
Date: Wed, 2 Mar 1994 11:33:17 GMT
Raw View
Helmut Jarausch (guest@igpm.rwth-aachen.de) wrote:

> class STR
> { char *text;
>   int  length;
>  public:
>   STR( const STR& Source );
>     // get space for a copy and copy text
>   STR( const STR& Source ) const { text= Source.text; length= Source.length; }
> };

Your second constructor would essentially create a second STR object that
used the same text buffer as the Source object. If the Source object were
were to be deleted, your 'const' object would have its pointer pointing at
garbage. This would be very bad.  I'm not sure I see the point to having
const constructors; this example certainly doesn't convince me it's needed.

Craig

--
      /----------------+-------------------------------------------------\
      | Craig Dickson  | So also the light that is absorbed. One absorbs |
      | crd@netcom.com | little, and is called white and glistening; one |
      |                | absorbs all and is called black.                |
      \----------------+-------------------------------------------------/