473,659 Members | 2,920 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamic_cast help?

I am trying to port a python program into c++ to more learn about
c++... so i am trying to do a MVC design.. so here is my events

class Event {
public:
Event() {}
Event(string text) { this->name = text; }

virtual string getName() { return this->name; }

string name;
};

class PlayerSelEvent : public Event {
public:
PlayerSelEvent( ) {}
PlayerSelEvent( string text, string player) : Event(text) {
this->player = player; }

virtual string getPlayer() { return this->player; }

string player;
};
now here is how a function gets it

void AppMasterContro ller::Notify(Ev ent *ev) {
std::cout << "got an event: " << ev->name << std::endl;

// checking the type
if (ev->getName() == "Set Player") {
PlayerSelEvent *nameEvent = dynamic_cast<Pl ayerSelEvent*>( ev);
std::cout << "players name is: " << nameEvent->getPlayer() <<
std::endl;
}
}

no the nameEvent->getPlayer() forces the program to quit due to a run
time error

am I doing it right to access the getPlayer() function?? or do I need
to do something else??

thanks
mike

Nov 22 '05 #1
2 1500
hi*****@gmail.c om wrote in news:1131859552 .209495.290960
@o13g2000cwo.go oglegroups.com:
I am trying to port a python program into c++ to more learn about
c++... so i am trying to do a MVC design.. so here is my events

class Event {
public:
Event() {}
Event(string text) { this->name = text; }
Should be passing text by const-ref. You're paying for an extra copy,
and prefer initialization to assignment:

Event(const string & text) : name(text) {}

virtual string getName() { return this->name; }

string name;
};

class PlayerSelEvent : public Event {
public:
PlayerSelEvent( ) {}
PlayerSelEvent( string text, string player) : Event(text) {
this->player = player; }
Same as above... pass by const-ref, and use initialization.

virtual string getPlayer() { return this->player; }

string player;
};
now here is how a function gets it

void AppMasterContro ller::Notify(Ev ent *ev) {
Hmm.. why are you accessing the name member directly in the next line,
but using the accessor function in the if statement?
std::cout << "got an event: " << ev->name << std::endl;

// checking the type
if (ev->getName() == "Set Player") {
PlayerSelEvent *nameEvent = dynamic_cast<Pl ayerSelEvent*> (ev); std::cout << "players name is: " << nameEvent->getPlayer() <<
std::endl;
}
}
Um, why not simply use the result of the dynamic_cast to find out if it's
the right type?:

PlayerSelEvent * nameEvent = dynamic_cast<Pl ayerSelEvent *>(ev);

if (nameEvent != NULL)
{
std::cout << "player's name is: " << nameEvent->getPlayer() <<
std::endl;
}

no the nameEvent->getPlayer() forces the program to quit due to a run
time error

am I doing it right to access the getPlayer() function?? or do I need
to do something else??


You didn't check the return value of the dynamic_cast to find out if it
succeeded or not.

You also haven't shown us how these events were created and passed into
this function (Notify). It may be possible that you're passing in an
event with the name "Set Player" that isn't actually a PlayerSelEvent.

Other items... any reason why the getName and getPlayer methods are
declared virtual? Are you intending subclasses to be able to change the
behaviour of those methods? Why no virtual destructor? (You haven't
shown the allocation/deallocation cycle of Events (and its
descendants)... I suspect you may be allocating a decendant and may be
deleteing it through the pointer to Event...). And... too much stuff is
public, like the name and player member variables.
Nov 22 '05 #2
<hi*****@gmail. com> wrote in message
news:11******** **************@ o13g2000cwo.goo glegroups.com
I am trying to port a python program into c++ to more learn about
c++... so i am trying to do a MVC design.. so here is my events

class Event {
public:
Event() {}
Event(string text) { this->name = text; }

virtual string getName() { return this->name; }

string name;
};

class PlayerSelEvent : public Event {
public:
PlayerSelEvent( ) {}
PlayerSelEvent( string text, string player) : Event(text) {
this->player = player; }

virtual string getPlayer() { return this->player; }

string player;
};
now here is how a function gets it

void AppMasterContro ller::Notify(Ev ent *ev) {
std::cout << "got an event: " << ev->name << std::endl;

// checking the type
if (ev->getName() == "Set Player") {
PlayerSelEvent *nameEvent = dynamic_cast<Pl ayerSelEvent*>( ev);
std::cout << "players name is: " << nameEvent->getPlayer() <<
std::endl;
}
}

no the nameEvent->getPlayer() forces the program to quit due to a run
time error

am I doing it right to access the getPlayer() function?? or do I need
to do something else??

thanks
mike


I don't know for sure what is causing your runtime error. Selected excerpts
from your code are rarely adequate to identify a problem. We are not
psychic. You should supply complete compileable code that exhibits the
problem. Often this will be a simplified version of your original code.

I will make a couple of points. First, dynamic casting is rarely needed in a
well written program. You can generally achieve the same effect in a less
error-prone way using virtual functions. Second, if you are to use dynamic
casting, then you might as well use all the power that it offers. You seem
to be duplicating its operation.

Judging by your code excerpt, you have a function that takes a base class
(Event) pointer as an argument. If the pointer actually points to a base
class object, you want the function to output only the name member from the
base class. If it points to a derived class (PlayerSelEvent ) object, you
want the function to output both the name member from the base class and the
player member from the derived class.

The simplest way to do this is with a virtual function, Display, defined as:

virtual void Display()
{
std::cout << "got an event: " << getName() << std::endl;
}

in Event and

virtual void Display()
{
Event::Display( );
std::cout << "players name is: " << getPlayer() << std::endl;
}

in PlayerSelEvent. Your Notify function is then simply:

void AppMasterContro ller::Notify(Ev ent *ev)
{
ev->Display();
}

Incidentally, pev is a much better name for a pointer to an Event than is
ev.

If this approach is not possible and you must use dynamic casting, then the
appropriate function definition is as follows:

void AppMasterContro ller::Notify(Ev ent *ev)
{
std::cout << "got an event: " << ev->name << std::endl;
PlayerSelEvent *nameEvent = dynamic_cast<Pl ayerSelEvent*>( ev);
if (nameEvent)
{
std::cout << "players name is: " << nameEvent->getPlayer() <<
std::endl;
}
}

The point here is that the result of dynamic casting will tell you what is
being pointed to. If it is a PlayerSelEvent object, then the casting works
and you get the address of the object. If it is an Event object, then the
casting fails and nameEvent will be zero, indicating that you should not
attempt to call nameEvent->getPlayer() (doing so will likely cause a runtime
error). Incidentally, nameEvent would be better called pnameEvent.

You seem to be attempting to test what is pointed to yourself by testing for
a name of "Set Player". If a base class object has this name, then your if()
condition succeeds, nameEvent becomes zero as a result of the dynamic cast,
and nameEvent->getPlayer() is then an error.
--
John Carson

Nov 22 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

13
4960
by: GianGuz | last post by:
Everyone knows about the complex and cpu-expensive procedures taken by dynamic_cast to find the right function call in a virtual classes hierarchy. The question I would to rise is when dynamic_cast is really necessary? A wise usage of templates and/or non dynamic_cast operators can grant the compiler with any information it needs to understand at compile time what is the right method to call. In the following example I tested the usage of...
3
1990
by: Axter | last post by:
I'm wondering about the practical use of dynamic_cast in reusable or generic code. I'm currently working on a smart pointer that can be used on vector and other STL containers. See following link: http://code.axter.com/arr_ptr.h In above code, there's a function called clone_func_ptr_interface within the func_ptr_holder class. In this function, I need to cast from a base pointer to a derived
1
1521
by: Steven T. Hatton | last post by:
The result shown below doesn't surprise me now. But it did several months ago when I followed some bad advice and tried to check if I had a live object at the address referenced by a pointer. Can I assume the result is consistente with the Standard? Tue May 10 21:24:24:> cat foo.cc #include <iostream> struct Foo{virtual ~Foo(){} }; struct Bar{virtual ~Bar(){} }; int main(){
3
2528
by: Ganesh | last post by:
On devx site, I saw following code. It says when a derived class is tried to cast to base type, it looks at the missing vtable and complains if the object is already deleted. I am of the opinion that this doesnt work if the destructor is not virtual or when the class has no virtual members. I would like to know is there anything wrong in what I am thinking. (I agree it is better to keep base class dtor as virtual, but supposing it is not...
5
8717
by: verec | last post by:
I just do not understand this error. Am I misusing dynamic_cast ? What I want to do is to have a single template construct (with no optional argument) so that it works for whatever T I want to use it with. Now, if that T happens to be some subclass of a known base class (object, in this case), I want to perform some extra stuff ... I've read Faq#35, and the most natural solution would have
22
4798
by: Boris | last post by:
I'm porting code from Windows to UNIX and ran into a problem with dynamic_cast. Imagine a class hierarchy with three levels: class Level2 derives from Level1 which derives from Base. If you look now at this code: Base *b = new Level2(); Level1 *l1 = dynamic_cast<Level1*>(b); Should dynamic_cast return a valid pointer or 0? I wonder as Visual Studio 2005 returns a valid pointer while g++ 3.4.6 returns 0. Both compilers work as expected...
15
2815
by: Grizlyk | last post by:
Hello. Returning to question of manual class type identification, tell me, for ordinary inheritance is C++ garantee that dynamic_cast<Derived*>(Base*) can be implemented similarly to return (Base*->type_fild >= Derived_typeid)? Base*: 0;
8
5427
by: pietromas | last post by:
In the example below, why does the dynamic_cast fail (return NULL)? It should be able to cast between sibling classes ... #include <iostream> class A { public: virtual const int get() const = 0;
9
1529
by: Rob | last post by:
(I am not the one who defined these classes) class _jobject {}; class _jarray : public _jobject {}; typedef _jobject* jobject; typedef _jarray jarray; int main() {
25
3127
by: lovecreatesbea... | last post by:
Suppose I have the following three classes, GrandBase <-- Base <-- Child <-- GrandChild The following cast expression holds true only if pBase points object of type of ``Child'' or ``GrandChild'', i.e. types not upper than Child in the above class hierarchy, dynamic_cast<Child*>pBase
0
8335
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8851
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8528
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8627
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
5649
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4175
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4335
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2752
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1976
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.