Topic: Temporaries in constructors


Author: gyro@kestrel.edu (Scott Layson Burson)
Date: 28 May 91 22:57:39 GMT
Raw View
In article <MARC.91May27140938@steve-dallas.mit.edu> marc@mit.edu (Marc Horowitz) writes:
>In article <1991May23.170530.23037@eua.ericsson.se> euaeny@eua.ericsson.se (Erik Nyquist) writes:
>
>   dsouza@gwen.cad.mcc.com (Desmond Dsouza) writes:
>
>   >In article <72461@microsoft.UUCP> jimad@microsoft.UUCP (Jim ADCOCK) writes:
>
>   >   >  You cannot compute any temporaries (e.g. common subexpressions)
>   >   >  which are needed for initialization of such data members.
>
>I'll start by saying that this problem should definitely be looked at.
>It apparently happens at least somewhat often, since it happened to me
>last night.  I had an even more difficult situation.  My classes look
>like this:
>
>class A {
>  public:
>    A(int a, int b, int c, int d);
>
>// ...
>};
>
>class B : public A {
>  public:
>    B(char *s)
>      :A(/* ??? */)
> { /* too late */ }
>
>// ...
>};
>
>void f(const char *s, int *a, int *b, int *c, int *d);
>
>f takes a string, and parses the integers out of it.  It's somewhat
>expensive.
>
>Now, how should I go about doing this?  Every solution I've been able
>to come up with is a morally abhorrent kludge involving some large
>number of static variables.  I really would like to be able to have a
>block where I could define a few local temporaries, call f, and pass
>those temps into the base constructor.  I could add another
>constructor to A, but A shouldn't need to depend on f, since f is
>really a part of B.

How about:

  class A {
    protected:
       A() {}
       void init(int a, int b, int c, int d);
       // ...
  };

  class B : public A {
    public:
       B(char* s) { int a, b, c, d; f(s, &a, &b, &c, &d);
                    init(a, b, c, d); }
  };

I'm not suggesting this is a perfect solution, but it sounds less
kludgey than any approach using static variables.

I think the message here is that the ctor-initializer mechanism is not
quite the right thing.  Seems to me the right approach would be
something more like allowing explicit base class constructor calls
within a derived class constructor?  Something like that.

-- Scott
Gyro@Reasoning.COM