er.. I don't know how "building" fit in your example. I'm assuming you meant red to be derived from color, not building. ;P
Is there anyway I can make a red pointer point to an instance of "red" using a color pointer as a reference? |
This is called "downcasting" can can be done with static_cast or dynamic_cast. It is somewhat dangerous to do this frivilously, because there's no guarantee that your color pointer actually points to a 'red'. It might point to a 'blue', or to a 'green', or to any other color.
static_cast assumes that you know
for a fact that the cast is legit. IE: your color* actually points to a red. If this is not the case you will have GRAVE and hard to find bugs in your program, so be
very careful when using static_cast this way:
1 2
|
color* colorptr = ...;
red* redptr = static_cast<red*>( colorptr );
|
dynamic_cast does a runtime check to ensure that the color pointer in fact points to a red object. If it doesn't, the cast will fail (null pointer returned). This is a little bit more CPU intensive, but is much safer:
1 2 3 4 5 6 7 8 9 10 11
|
color* colorptr = ...;
red* redptr = dynamic_cast<red*>( colorptr );
if( !redptr )
{
// colorptr did not point to a red
}
else
{
// cast okay!
}
|
If not, should I just stick to using pointers of the parent classes only? |
No
Use whatever is appropriate to the situation.
If you are writing code that is meant to work with ANY color, then use a color*. But if you are writing code that will only work with a red, then use a red*.
Believe it or not, the need for downcasting doesn't come up as often as you might think, if your class hierarchies are carefully designed.
No, it just makes your code harder to follow and more bug prone.