Path: utzoo!utgpu!jarvis.csri.toronto.edu!rutgers!att!mtuxo!mtgzz!drutx!druco!jrb From: jrb@druco.ATT.COM (John Behrs) Newsgroups: comp.lang.c++ Subject: Question: Object transformations in C++ Message-ID: <4413@druco.ATT.COM> Date: 20 Jun 89 17:19:19 GMT Distribution: comp Organization: The Right Choice Lines: 57 How can an instantiation of one derived class transform into a different derived class of the same base class? The derived classes have different virtual functions but have no additional private data, so what I really would like to do is just change the "virtual" type field. Below is some code that I hope illustrates the problem. // // Class transformations // #include class base { int base_a; int base_b; public: base(int a, int b) { base_a = a; base_b = b; } int a() { return base_a; } int b() { return base_b; } virtual void func() {} }; class x:public base { public: x(int a, int b) : (a, b) {} void func() { cout << "X"; } }; class y:public base { public: y(int a, int b) : (a, b) {} void func() { cout << "Y"; } }; main() { class x x1(5,10); x1.func(); // prints 'X' // // Assuming class x and class y to have identical data structure, // convert x1 to be of class y // // (I'd much rather change just the virtual type field, // but I don't know how.) // { class y y1(x1.a(), x1.b()); x1 = *(class x *)&y1; } // // x1 is now of class y // x1.func(); // prints 'Y' } -- "What's the point of being alive, | John Behrs if you're not going to communicate?" | druco!jrb -- Kurt Vonnegut, Bluebeard. | (303) 538-3539