473,503 Members | 2,163 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 AppMasterController::Notify(Event *ev) {
std::cout << "got an event: " << ev->name << std::endl;

// checking the type
if (ev->getName() == "Set Player") {
PlayerSelEvent *nameEvent = dynamic_cast<PlayerSelEvent*>(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 1481
hi*****@gmail.com wrote in news:1131859552.209495.290960
@o13g2000cwo.googlegroups.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 AppMasterController::Notify(Event *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<PlayerSelEvent*> (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<PlayerSelEvent *>(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.googlegr oups.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 AppMasterController::Notify(Event *ev) {
std::cout << "got an event: " << ev->name << std::endl;

// checking the type
if (ev->getName() == "Set Player") {
PlayerSelEvent *nameEvent = dynamic_cast<PlayerSelEvent*>(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 AppMasterController::Notify(Event *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 AppMasterController::Notify(Event *ev)
{
std::cout << "got an event: " << ev->name << std::endl;
PlayerSelEvent *nameEvent = dynamic_cast<PlayerSelEvent*>(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
4940
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...
3
1985
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...
1
1508
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...
3
2524
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...
5
8689
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...
22
4779
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...
15
2803
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 ...
8
5412
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()...
9
1519
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
3102
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...
0
7093
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...
0
7287
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,...
1
7011
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...
0
5596
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
5023
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4689
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...
0
3180
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...
0
3170
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1521
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 ...

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.