home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / cplus / 12775 < prev    next >
Encoding:
Text File  |  1992-08-23  |  1.6 KB  |  50 lines

  1. Newsgroups: comp.lang.c++
  2. Path: sparky!uunet!taumet!steve
  3. From: steve@taumet.com (Steve Clamage)
  4. Subject: Re: constructor call during initialization of same class
  5. Message-ID: <1992Aug23.154530.1131@taumet.com>
  6. Organization: TauMetric Corporation
  7. References: <1992Aug23.030355.23047@athena.mit.edu>
  8. Date: Sun, 23 Aug 1992 15:45:30 GMT
  9. Lines: 39
  10.  
  11. casadei@verona.mit.edu (Stefano Casadei) writes:
  12.  
  13. >Is it possible to define a class constructor which invokes another
  14. >constructor of the same class during the initialization phase (i.e. between
  15. >the : and the body) ? If not, why is such a simple feature not implemented
  16. >in the language ?
  17.  
  18. A constructor turns raw storage or an object of some type into the
  19. constructor's object type.  You may invoke a constructor to create
  20. an object from inside a constructor:
  21.     class foo { ... foo(); foo(int); }
  22.     foo *fp;
  23.     foo::foo()
  24.     {
  25.         foo f(1);    // create another foo 'f' inside the constructor
  26.         fp = new foo(2);    // create another foo on the heap
  27.     }
  28. Of course, the local foo 'f' created inside foo::foo() is destroyed when
  29. foo::foo() exits.
  30.  
  31. I am guessing that you want to share some code by having several
  32. constructors call a "basic" constructor.  You can't do that with
  33. a construcutor.  You can write an initialization function which all
  34. constructors call.  This is equivalent to what I think you want:
  35.     class foo {
  36.     public:
  37.         foo();
  38.         foo(int);
  39.         foo(char*);
  40.     private:
  41.         init();
  42.     }
  43.     foo::foo() { ... init(); ... }
  44.     foo::foo(int i) { ... init(); ... }
  45.     foo::foo(char* p) { ... init(); ... }
  46. -- 
  47.  
  48. Steve Clamage, TauMetric Corp, steve@taumet.com
  49. Vice Chair, ANSI C++ Committee, X3J16
  50.