home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: sparky!uunet!taumet!steve
- From: steve@taumet.com (Steve Clamage)
- Subject: Re: Is this C++ advice from an OO book true? (beginner question)
- Message-ID: <1993Jan24.163907.18298@taumet.com>
- Organization: TauMetric Corporation
- References: <sherman.727849469@foster>
- Date: Sun, 24 Jan 1993 16:39:07 GMT
- Lines: 50
-
- sherman@unx.sas.com (Chris Sherman) writes:
-
- > 11. Call virtual class constructors in dervied class constructors.
-
- > I pity the poor fools who have to spend nights and weekends searching
- > for the reason that a class variable occasionally takes on strange,
- > unexpected values . . . only to find through their bleary eyes
- > that they forgot to allocate space for a virtual base (super) class,
- > so that storage is allocated for the base class's members. Even if
- > the class has no members, declare it--you never know what future
- > changes will come back to haunt you (or the person who inherits your
- > mine field)!
-
- Let's assume the wording is poor and the writer means "call the constructor
- for virtual base classes in derived class constructors". This is not
- necessarily bad advice, but the reason given is nonsensical.
-
- The constructors for all virtual base classes in a hierarchy are called
- when beginning construction of the entire (most-derived) object. If
- the most-derived constructor does not specify which constructor to call
- for a virtual base class, the default constructor will be called. This
- is the case even if an intermediate class appears to invoke a particular
- base class constructor. Simple example:
-
- class Base { ... Base(); Base(int); };
- class D1 : public virtual Base {
- ...
- D1(int i) : Base(i) { ... };
- };
- class D2 : public D1 {
- ...
- D2(int i) : D1(i) { ... }
- };
- D2 d(2);
-
- When constructing object d, there is no explicit invocation of a Base
- constructor in D2::D2(int), so Base::Base() is invoked. This might seem
- surprising if you don't know the rule. If Base did not have a default
- constructor, the example would not even compile.
-
- You can call out explicitly the virtual base class constructors if you wish:
- D2(int i) : Base(i), D1(i) { ... }
- This is necessary if you want a particular constructor for a virtual base
- class, since you will otherwise get the default initializer (or an error).
-
- On the other hand, if you intend for the default constructor to be called,
- you need do nothing, since that is what you will get.
- --
-
- Steve Clamage, TauMetric Corp, steve@taumet.com
-