home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!UB.com!igor!thor!rmartin
- From: rmartin@thor.Rational.COM (Bob Martin)
- Newsgroups: comp.lang.c++
- Subject: Re: copy ctor and inheritance
- Message-ID: <rmartin.715615056@thor>
- Date: 4 Sep 92 13:57:36 GMT
- References: <6143@taurus.cs.nps.navy.mil>
- Sender: news@Rational.COM
- Lines: 54
-
- skip@taygeta.oc.nps.navy.mil (Skip Carter) writes:
-
-
- | How do I get the copy constructor of a base class to get invoked
- | when I use a copy constructor for a base class ?
-
- | In the following example I get the behaviour I want (AT&T 2.1)
- | if I leave it up to the compiler to create the copy constructor for B,
- | but if I write my own, the copy constructor for the base class A never
- | gets invoked. (It does not matter whether or not I define the copy constructor
- | for the base class, A).
-
-
- You invoke the base class copy constructor in the initialization list
- of the derived class. See the modification that I made to your code
- sample below. And remember, never use gotos.
-
- |#include <iostream.h>
-
- |class A
- |{
- | private:
- | int val;
- | public:
- | A() : val(0) { cout << "A() invoked\n"; }
- | A(const A& a) { val = a.val; cout << "A(&A) invoked, val = " << val << '\n'; }
- | ~A() { cout << "A.val = " << val << " going away\n"; }
- | void set_val(const int v) { val = v; }
- | int get_val() const { return val; }
- |};
-
- |class B : public A
- |{
- | private:
- | int vv;
- | public:
- | B() : vv(0) { cout << "B() invoked\n"; }
-
- | B(const B& b) : A(b) { vv = b.vv; cout << "B(&B) invoked\n"; }
- ^^^^^^
- ------------------------------
-
- | ~B() { cout << "B.val = " << vv << '\t' << get_val() << " going away\n"; }
- | void set_v(const int v) { vv = v; }
- | int get_v() const { return vv; }
- |};
-
-
-
- --
- Robert Martin Training courses offered in:
- R. C. M. Consulting Object Oriented Analysis
- 2080 Cranbrook Rd. Object Oriented Design
- Green Oaks, Il 60048 (708) 918-1004 C++
-