calling function which takes parent pointer and sending it a child pointer

Started by
4 comments, last by graveyard filla 19 years, 3 months ago
hi, lets say we have this:

class Dad
{
};

class Son : public Dad
{
};

void some_function(Son *son);

now, we try to do this:

Dad *dad = new Dad();

some_function(dad);
this wont compile? why not? and is there any trick to get this to work without casting or RTTI? thanks for any help.
FTA, my 2D futuristic action MMORPG
Advertisement
Compiles fine for me. What error message are you getting?
sorry, its 5 in the morning and im a little out of it.. edited my post so it made more sence (hopefully) [grin]
FTA, my 2D futuristic action MMORPG
It won't compile because a Dad is not a Son. If you could get it to work with casting somehow, if some_function() uses member variables that are in Son and not in Dad, then you've got some bad mojo as the program reads or writes to memory that wasn't allocated as part of the Dad.
class Dad {}class Son : public Dad {}class Daughter : public Dad {}void some_function(Son *son);Dad *d = new Daughter;some_function((Son*) d);


Bad mojo indeed.

Find some other way to solve the problem if possible. For example, part of some_function() might be made into a virtual in Dad, and then overridden in Son. On the other hand, if you *know* the object is a Son, you should probably be using a pointer to a Son in the first place.

Pick it up - play with it - twist it around - repeat until it's no longer nasty :)
ok..

i think i need to stop coding after a certain time at night [smile]. i know an easy fix for this, just change the function to take a Dad, since it only messes with Dad members anyway.. i dunno what i was thinking.. thanks.
FTA, my 2D futuristic action MMORPG

This topic is closed to new replies.

Advertisement