home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #19 / NN_1992_19.iso / spool / comp / lang / cplus / 13295 < prev    next >
Encoding:
Internet Message Format  |  1992-09-04  |  1.9 KB

  1. Path: sparky!uunet!UB.com!igor!thor!rmartin
  2. From: rmartin@thor.Rational.COM (Bob Martin)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: copy ctor and inheritance
  5. Message-ID: <rmartin.715615056@thor>
  6. Date: 4 Sep 92 13:57:36 GMT
  7. References: <6143@taurus.cs.nps.navy.mil>
  8. Sender: news@Rational.COM
  9. Lines: 54
  10.  
  11. skip@taygeta.oc.nps.navy.mil (Skip Carter) writes:
  12.  
  13.  
  14. |    How do I get the copy constructor of a base class to get invoked
  15. |    when I use a copy constructor for a base class ?
  16.  
  17. |    In the following example I get the behaviour I want (AT&T 2.1)
  18. |    if I leave it up to the compiler to create the copy constructor for B,
  19. |    but if I write my own, the copy constructor for the base class A never
  20. |    gets invoked.  (It does not matter whether or not I define the copy constructor
  21. |    for the base class, A).
  22.  
  23.  
  24. You invoke the base class copy constructor in the initialization list
  25. of the derived class.  See the modification that I made to your code
  26. sample below.  And remember, never use gotos.
  27.  
  28. |#include <iostream.h>
  29.  
  30. |class A
  31. |{
  32. |    private:
  33. |      int val;
  34. |    public:
  35. |      A() : val(0) { cout << "A() invoked\n"; }
  36. |      A(const A& a) { val = a.val; cout << "A(&A) invoked,  val = " << val << '\n'; }
  37. |     ~A() { cout << "A.val = " << val << " going away\n"; }
  38. |      void set_val(const int v) { val = v; }
  39. |      int get_val() const { return val; }
  40. |};
  41.  
  42. |class B : public A
  43. |{
  44. |    private:
  45. |       int vv;
  46. |    public:
  47. |      B() : vv(0) { cout << "B() invoked\n"; }
  48.  
  49. |      B(const B& b) : A(b) { vv = b.vv; cout << "B(&B) invoked\n"; }
  50.                         ^^^^^^
  51. ------------------------------
  52.  
  53. |     ~B() { cout << "B.val = " << vv << '\t' << get_val() << " going away\n"; }
  54. |      void set_v(const int v) { vv = v; }
  55. |      int get_v() const { return vv; }
  56. |};
  57.  
  58.  
  59.  
  60. --
  61. Robert Martin                        Training courses offered in:
  62. R. C. M. Consulting                       Object Oriented Analysis
  63. 2080 Cranbrook Rd.                        Object Oriented Design
  64. Green Oaks, Il 60048 (708) 918-1004       C++
  65.