c++ - Using an intermediate result to initialise several attributes -


i have class constructor this:

class b; class c; class d;    class a{ private:   b b;   c c;  public:   a(istream& input){     d d(input) // build d based on input     b = b(d);  // use d build b     c = c(d);  // , c   } } 

which should work fine long b , c have default constructors.

my problem b doesn't, need initialise b in initialisation list. issue since need build d before can compute b , c.

one way this:

a(istream& input):b(d(input)),c(d(input)){} 

but building d (very) costly (*)

what's clean way around problem?


(*)another problem if b , c need built same instance (like if d's constructor randomized or whatever). that's not case though.

in c++11 use delegating constructors:

class b; class c; class d;  class { private:      b b;     c c;  public:      explicit a(istream& input)         :         a(d(input))     {     }      // if wish, make protected or private     explicit a(d const& d)         :         b(d),         c(d)     {     } }; 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -