![]() |
|
|
|
Thread Tools | Display Modes |
|
|
|
|
#1 |
|
Newbie
Join Date: Apr 2005
Posts: 6
Rep Power: 0
![]() |
Virtual functions on casted objects
I've used virtual functions before, but never in this way, and am not getting the sort of behavior I was expecting. Can someone offer some advice?
Here is some test code. We define a base class, and a class that inherits from it. One function gets changed; all they do is print so we know which function is being called (the parent class's or the child class's). We then try various things in the main function. #include <string> #include <iostream> using namespace std; class Base { public: Base() {}; virtual ~Base() {}; virtual void blah() { cout << "Base" << endl; }; }; class Extended: public Base { public: Extended() {}; ~Extended() {}; void blah() { cout << "Extended" << endl; }; }; int main(int argc, char** argv) { Base().blah(); Extended().blah(); Extended e; e.blah(); Base b=Extended(); ((Extended&)b).blah(); ((Extended*)&b)->blah(); return 0; } Output: Base Extended Extended Base Base Now, the first three things are as we'd expect. However, I expect the latter two, since they're being cast to Expected, to print "Expected". Why aren't they? Is there no way that I can cast them back to their original object? Here's what I'm trying to do in the real world: I am writing an implementation of a networking protocol. Each level is an object, which holds any child packets. If there are multiple possible child packets, it holds a basic child packet, and the different types inherit from it and are stored in the basic child variable, and cast as needed. When we want to send the data, they all serialize themselves into a string that gets sent. So... I must be doing something wrong, but I know not what. Any help would be appreciated. ![]() |
|
|
|
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|