Jump to content
  • Advertisement
Sign in to follow this  
graveyard filla

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

This topic is 4947 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
Advertisement
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
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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!