home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!sun-barr!cs.utexas.edu!zaphod.mps.ohio-state.edu!pacific.mps.ohio-state.edu!linac!uwm.edu!lll-winken!taurus!taygeta.oc.nps.navy.mil!skip
- From: skip@taygeta.oc.nps.navy.mil (Skip Carter)
- Newsgroups: comp.lang.c++
- Subject: copy ctor and inheritance
- Message-ID: <6143@taurus.cs.nps.navy.mil>
- Date: 3 Sep 92 17:41:37 GMT
- Sender: news@taurus.cs.nps.navy.mil
- Reply-To: skip@taygeta.oc.nps.navy.mil (Skip Carter)
- Lines: 72
-
-
- 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).
-
-
- #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"; }
-
- // If the constructor below is commented out, A::val is copied
- // B(const B& 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; }
- };
-
- void main()
- {
- A a;
-
- a.set_val( 3 );
-
- B b;
-
- b.set_v( 2 );
-
- b.set_val( 1 );
-
- // no surprises here
- cout << "A = " << a.get_val() << endl;
- cout << "B = " << b.get_v() << '\t' << b.get_val() << endl;
-
-
- // now for the real test
-
- B c( b );
-
- cout << "C = " << c.get_v() << '\t' << c.get_val() << endl;
-
- }
-
-
- --
-
- Everett (Skip) Carter Phone: 408-646-3318 FAX: 408-646-2712
- Naval Postgraduate School INTERNET: skip@taygeta.oc.nps.navy.mil
- Dept. of Oceanography, Code OC/CR UUCP: ...!uunet!taygeta!skip
- Monterey, CA. 93943 TELEMAIL: s.carter/omnet
-