Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Apr 10th, 2005, 2:16 AM   #1
Rei
Newbie
 
Join Date: Apr 2005
Posts: 6
Rep Power: 0 Rei is on a distinguished road
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.
Rei is offline   Reply With Quote
Old Apr 10th, 2005, 7:44 AM   #2
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
Pointers are your friends.
Try
Base *b = new Extended();
b->blah();
Cerulean is offline   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 10:05 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC