home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!crdgw1!rpi!uwm.edu!spool.mu.edu!agate!doc.ic.ac.uk!pipex!demon!trmphrst.demon.co.uk!nikki
- From: nikki@trmphrst.demon.co.uk (Nikki Locke)
- Newsgroups: comp.lang.c++
- Subject: Re: Is this C++ advice from an OO book true? (beginner question)
- Message-ID: <728159910snx@trmphrst.demon.co.uk>
- Date: 27 Jan 93 11:38:30 GMT
- References: <BAB.93Jan24100815@se39.wg2.waii.com> <sherman.727849469@foster> <dak.727870302@tabaqui>
- Sender: usenet@demon.co.uk
- Reply-To: nikki@trmphrst.demon.co.uk
- Organization: Trumphurst Ltd.
- Lines: 38
- X-Mailer: cppnews $Revision: 1.31 $
-
- In article <BAB.93Jan24100815@se39.wg2.waii.com> bab@se39.wg2.waii.com (Brian Button) writes:
- > I don' think the question was why to call a virtual constructor for a
- > base class, but why to call a constructor for a virtual base class.
- >
- > These constructors need to be called to ensure that the data members
- > of any parent classes are properly initialized. For instance:
- >
- > class VirtBase
- > {
- > private:
- > int a;
- >
- > protected:
- > int myA( ) const { return a; }
- > int myA( const int anA ) { return a = anA; }
- >
- > public:
- > VirtBase( const int anA ) : a( anA ) { }
- > };
- >
- > class DerivedClass : virtual public VirtBase
- > {
- > public:
- > DerivedClass( const int anA ) : VirtBase( anA ) { }
- > };
- >
- > If VirtBase weren't initialized in the constructor for DerivedClass,
- > VirtBase::a would never be initialized. This is one reason why you
- > should always explicitly call the constructor for any base classes in
- > a derived classes constructor.
-
- In your example, if "VirtBase weren't initialized in the constructor for
- DerivedClass", then the program would not compile, as VirtBase does not
- have a default constructor.
-
- --
- Nikki Locke,Trumphurst Ltd.(PC and Unix consultancy) nikki@trmphrst.demon.co.uk
- trmphrst.demon.co.uk is NOT affiliated with ANY other sites at demon.co.uk.
-