Sign in to follow this  

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

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.

Share this post


Link to post
Share on other sites

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 :)

Share this post


Link to post
Share on other sites

This topic is 4733 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this