home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- From: nikki@trmphrst.demon.co.uk (Nikki Locke)
- Path: sparky!uunet!pipex!demon!trmphrst.demon.co.uk!nikki
- Subject: Re: operator = with inheritance
- Reply-To: nikki@trmphrst.demon.co.uk
- References: <1993Jan20.221834.26489@murdoch.acc.Virginia.EDU> <1993Jan14.184649.17113@ucc.su.OZ.AU>
- Distribution: world
- X-Mailer: cppnews $Revision: 1.31 $
- Organization: Trumphurst Ltd.
- Lines: 84
- Date: Fri, 22 Jan 1993 15:13:40 +0000
- Message-ID: <727740820snx@trmphrst.demon.co.uk>
- Sender: usenet@demon.co.uk
-
- In article <1993Jan20.221834.26489@murdoch.acc.Virginia.EDU> gs4t@virginia.edu (Gnanasekaran Swaminathan) writes:
- > nikki@trmphrst.demon.co.uk (Nikki Locke) writes:
- > : But this unfortunately fails the test from the previous posting ...
- >
- > It works fine. Note the assign op is also virtual.
- >
- > Since assign op is virtual, B::op = (a2) is called for
- > reference a1. B::op = (a2), in turn, calls B::copy2 (this).
- >
- > g++ compiler gets this wrong. Probably try a different compiler
- > if you are using g++.
- I am afraid I think it is YOU who has got it wrong !
-
- I tested the program at the end of this post under Zortech c++ 3.0r4,
- Borland C++ 3.0, and Microsoft C7, and they all gave the following output ...
-
- B::=(A&)
- B::copy2(A*)
- A::copy2(A*)
- b1.b = 11 b2.b = 22 b1.a = 2 b2.a = 2
-
- If you follow this through,
- a1=a2; calls the virtual operator B::operator=(const A&)
- B::operator=(const A&) calls virtual function B::copy2(A*), NOT B::copy2(B*),
- because polymorphism doesn't act on function arguments.
-
- Did you actually test this on some compiler ? If so, which one ?
- _I_ think it has a bug !
- --
- 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.
- ----------------------- cut here -------------------------
- #include <iostream.h>
-
- class A {
- public:
- int a;
- virtual void copy2 (A* c) const { c->a = a; cout << "A::copy2(A*)\n"; }
- A (int c): a(c) {}
- virtual A& operator = (const A& c) {
- if (this != &c) { // testing for assignment to the same object
- cout << "A::=(A&)\n";
- c.copy2 (this);
- }
- return *this;
- }
- };
-
- class B: public A {
- public:
- int b;
- virtual void copy2 (A* c) const { cout << "B::copy2(A*)\n"; A::copy2 (c); }
- virtual void copy2 (B* c) const { cout << "B::copy2(B*)\n"; A::copy2 (c); c->b = b; }
- B (int c): A(c), b(2*c) {}
- A& operator = (const A& c) {
- if (this != &c) {
- cout << "B::=(A&)\n";
- c.copy2 (this);
- }
- return *this;
- }
- };
-
- main()
- {
- B b1(1);
- B b2(2);
-
- b1.a=1;
- b1.b=11;
- b2.a=2;
- b2.b=22;
-
- A &a1=b1;
- A &a2=b2;
-
- a1=a2; // OH! only assigns the 'A' subobject of B.
- // A::op= (a), A::copy2 (A* &a)
- cout << "b1.b = " << b1.b << " b2.b = " << b2.b << " b1.a = " << b1.a <<
- " b2.a = " << b2.a << "\n";
- return 0;
- }
-
-
-