((derived *)base_pointer)->vfunc();
In my program this still seems to call the base class's vfunc(). Is there another method of doing this? dynamic_cast?
JoeDark
Edited by - JoeDark on January 25, 2001 3:12:07 AM
Virtual Functions and Casting
Is there a way to cast an object to a derived class and call the derived classes virtual function? Like:
JoeDark, if you call a virtual function it will always call the derived classes function, not the base. The problem is probably in your function definition. If you could paste your class definition so we could look at it...
- Houdini
- Houdini
- Houdini
You must make the function virtual, just put the word virtual in front of the function definition in the class-definition, like:
|
BTW, just to add to what amag said, you don''t NEED the virtual keyword in your derived classes, but I would always recommend including it. Otherwise when your project gets larger you may not remember if a function is virtual in the class, and instead of just looking at the header you have to burrow down till you find your base class just to find out.
It''s also EXTREMELY helpful when editing someone elses code.
- Houdini
It''s also EXTREMELY helpful when editing someone elses code.
- Houdini
- Houdini
Here's how the classes are defined:
And in one of my init functions I basically have:
And both of the calls to init_random() seem to call the base function.
JoeDark
Edited by - JoeDark on January 25, 2001 10:52:30 AM
Edited by - JoeDark on January 25, 2001 10:54:18 AM
Edited by - JoeDark on January 25, 2001 10:55:45 AM
Edited by - JoeDark on January 25, 2001 10:56:59 AM
|
And in one of my init functions I basically have:
|
And both of the calls to init_random() seem to call the base function.
JoeDark
Edited by - JoeDark on January 25, 2001 10:52:30 AM
Edited by - JoeDark on January 25, 2001 10:54:18 AM
Edited by - JoeDark on January 25, 2001 10:55:45 AM
Edited by - JoeDark on January 25, 2001 10:56:59 AM
January 25, 2001 10:00 AM
For the derived class''s virtual function to be called, you must allocate a derived class instance, ie not
e_pointer = new entity;
but
e_pointer = new startport;
Then it should be ok.
belette/wipe
www.wipe-fr.org
e_pointer = new entity;
but
e_pointer = new startport;
Then it should be ok.
belette/wipe
www.wipe-fr.org
AP is correct, but just to clarify so you aren''t confused:
should be
Notice that it''s still declared as ''entity *'' but is newed as ''starport''.
- Houdini
entity *e_pointer;e_pointer = new entity;e_pointer->init_random();
should be
entity *e_pointer;e_pointer = new starport;e_pointer->init_random();
Notice that it''s still declared as ''entity *'' but is newed as ''starport''.
- Houdini
- Houdini
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement
Recommended Tutorials
Advertisement