home bbs files messages ]

Forums before death by AOL, social media and spammers... "We can't have nice things"

   comp.lang.c++.moderated      Moderated discussion of C++ superhackery      33,346 messages   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]

   Message 32,209 of 33,346   
   Dave Abrahams to All   
   Re: Initialization and trivial construct   
   27 Apr 12 11:29:10   
   
   From: dave@boostpro.com   
      
   on Thu Apr 26 2012, "Martin B." <0xCDCDCDCD-AT-gmx.at> wrote:   
      
   >> Yes, for example:   
   >>   
   >> A::A(double x, double y, double r = hypot(x, y))   
   >> : x(x/r), y(y/r)   
   >> {   
   >> }   
   >>   
   >> But I would also suggest that the constructor might not need to have   
   >> the burden of doing those calculations in the first place, it's more   
   >> common for a constructor to initialize its members directly from   
   >> constructor parameters:   
   >>   
   >> A::A(double x, double y) : x(x), y(y) {}   
   >>   
   >> and make the caller responsible for providing the expected parameters:   
   >>   
   >> double r = hypot(x, y);   
   >> A(x/r, y/r);   
   >>   
   >   
   > Both your (counter-)examples are *not* convincing. They significantly   
   > change what the constructor does. (In that a user could provide another   
   > r / in that the hypot() function is leaked into the interface.)   
      
   I agree that this is "jumping through hoops", but there is a standard   
   way to deal with that problem: use delegating constructors:   
      
      struct A   
      {   
          A(double x, double y)   
            : A(x,y,hypot(x, y)) {}   
      
        private:   
          A(double x, double y, double r)   
            :x(x/r), y(y/r) {}   
      
            double x, y;   
      };   
      
   in C++03, you do the same thing by adding a base class just for   
   construction purposes:   
      
      struct ABase   
      {   
          A(double x, double y, double r)   
            :x(x/r), y(y/r) {}   
      
            double x, y;   
      };   
      
      struct A : private ABase   
      {   
          A(double x, double y)   
            : ABase(x,y,hypot(x, y)) {}   
      };   
      
   --   
   Dave Abrahams   
   BoostPro Computing   
   http://www.boostpro.com   
      
      
         [ See http://www.gotw.ca/resources/clcm.htm for info about ]   
         [ comp.lang.c++.moderated.    First time posters: Do this! ]   
      
   --- SoupGate-Win32 v1.05   
    * Origin: you cannot sedate... all the things you hate (1:229/2)   

[   << oldest   |   < older   |   list   |   newer >   |   newest >>   ]


(c) 1994,  bbs@darkrealms.ca