home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: constructor call during initialization of same class
- Message-ID: <1992Aug23.154530.1131@taumet.com>
- Organization: TauMetric Corporation
- References: <1992Aug23.030355.23047@athena.mit.edu>
- Date: Sun, 23 Aug 1992 15:45:30 GMT
- Lines: 39
-
- casadei@verona.mit.edu (Stefano Casadei) writes:
-
- >Is it possible to define a class constructor which invokes another
- >constructor of the same class during the initialization phase (i.e. between
- >the : and the body) ? If not, why is such a simple feature not implemented
- >in the language ?
-
- A constructor turns raw storage or an object of some type into the
- constructor's object type. You may invoke a constructor to create
- an object from inside a constructor:
- class foo { ... foo(); foo(int); }
- foo *fp;
- foo::foo()
- {
- foo f(1); // create another foo 'f' inside the constructor
- fp = new foo(2); // create another foo on the heap
- }
- Of course, the local foo 'f' created inside foo::foo() is destroyed when
- foo::foo() exits.
-
- I am guessing that you want to share some code by having several
- constructors call a "basic" constructor. You can't do that with
- a construcutor. You can write an initialization function which all
- constructors call. This is equivalent to what I think you want:
- class foo {
- public:
- foo();
- foo(int);
- foo(char*);
- private:
- init();
- }
- foo::foo() { ... init(); ... }
- foo::foo(int i) { ... init(); ... }
- foo::foo(char* p) { ... init(); ... }
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
- Vice Chair, ANSI C++ Committee, X3J16
-