home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!mcsun!Germany.EU.net!ira.uka.de!slsvaat!us-es.sel.de!kanze
- From: kanze@us-es.sel.de (James Kanze)
- Subject: Re: constructor call during initialization of same class
- Message-ID: <1992Aug28.141327.11921@us-es.sel.de>
- Sender: news@us-es.sel.de
- Organization: SEL-Alcatel LTS Dept. US/ES
- References: <1992Aug23.030355.23047@athena.mit.edu> <1992Aug23.154530.1131@taumet.com> <1992Aug27.182902.2022@us-es.sel.de>
- Date: Fri, 28 Aug 92 14:13:27 GMT
- Lines: 44
-
- I'm reposting the following, since I notice that I forgot to correct the distribution
- in the initial post. (We default to a local distribution here.)
-
- In article <1992Aug23.154530.1131@taumet.com>, steve@taumet.com (Steve Clamage) writes:
- |> 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 ?
-
- [...]
-
- |> 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(); ... }
-
- Actually, I think you *can* call a constructor (for the same object)
- within a constructor. If not, what does the following code do:
-
- foo::foo(int i) { ... ; new (this) foo ; ... }
-
- On the other hand, I don't think you really want to. To begin with,
- the syntax is, to say the least , unpleasant. And what happens if
- foo is a derived class: the constructor for the base class gets called
- twice, without an intervening destructor. That could lead to some
- unpleasantness too.
- --
- James Kanze GABI Software, Sarl.
- email: kanze@us-es.sel.de 8 rue du Faisan
- 67000 Strasbourg
- France
-