home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1993 #3 / NN_1993_3.iso / spool / comp / lang / cplus / 20081 < prev    next >
Encoding:
Internet Message Format  |  1993-01-28  |  1.9 KB

  1. Path: sparky!uunet!crdgw1!rpi!uwm.edu!spool.mu.edu!agate!doc.ic.ac.uk!pipex!demon!trmphrst.demon.co.uk!nikki
  2. From: nikki@trmphrst.demon.co.uk (Nikki Locke)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Is this C++ advice from an OO book true? (beginner question)
  5. Message-ID: <728159910snx@trmphrst.demon.co.uk>
  6. Date: 27 Jan 93 11:38:30 GMT
  7. References: <BAB.93Jan24100815@se39.wg2.waii.com> <sherman.727849469@foster> <dak.727870302@tabaqui>
  8. Sender: usenet@demon.co.uk
  9. Reply-To: nikki@trmphrst.demon.co.uk
  10. Organization: Trumphurst Ltd.
  11. Lines: 38
  12. X-Mailer: cppnews $Revision: 1.31 $
  13.  
  14. In article <BAB.93Jan24100815@se39.wg2.waii.com> bab@se39.wg2.waii.com (Brian Button) writes:
  15. > I don' think the question was why to call a virtual constructor for a
  16. > base class, but why to call a constructor for a virtual base class.
  17. > These constructors need to be called to ensure that the data members
  18. > of any parent classes are properly initialized. For instance:
  19. > class VirtBase
  20. > {
  21. >   private:
  22. >     int     a;
  23. >   protected:
  24. >     int     myA( ) const            { return a; }
  25. >     int     myA( const int anA )    { return a = anA; }
  26. >   public:
  27. >     VirtBase( const int anA ) : a( anA ) { }
  28. > };
  29. > class DerivedClass : virtual public VirtBase
  30. > {
  31. >   public:
  32. >     DerivedClass( const int anA ) : VirtBase( anA ) { }
  33. > };
  34. > If VirtBase weren't initialized in the constructor for DerivedClass,
  35. > VirtBase::a would never be initialized. This is one reason why you
  36. > should always explicitly call the constructor for any base classes in
  37. > a derived classes constructor.
  38.  
  39. In your example, if "VirtBase weren't initialized in the constructor for
  40. DerivedClass", then the program would not compile, as VirtBase does not 
  41. have a default constructor.
  42.  
  43. -- 
  44. Nikki Locke,Trumphurst Ltd.(PC and Unix consultancy) nikki@trmphrst.demon.co.uk
  45. trmphrst.demon.co.uk is NOT affiliated with ANY other sites at demon.co.uk.
  46.