Inheritance and using in functions

Hey all,

I've been playing around with inheritance and i have a big collision detection function that compares 2 types of object.

Just recently i had written a new object that inherits features from one of these objects.

I was fully expecting to be able to use my old function with this new object type because it has all the same features as the inherited class.

In code form:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class primaryobj{
//some features
}*obj1;

class secondaryobj: public primaryobj{
//some features
}*obj2;

class tertiaryobj: public secondaryobj{
//somefeatures
}*obj3; 

somefunction(primaryobj *a, secondaryobj *b){
//some process
}

main(){
   somefunction(obj1,obj2);//works fine

   somefunction(obj1,obj3);//doesn't work expects a secondary obj.

}


Ok so I understand this is obviously a bit of an in theory question but why exactly can't the function
take a tertiaryobj instead of a secondary as tertiary is guaranteed to have all the features of a secondary.

Is there a way around this without rewriting out my whole function?

Thanks for any help.


Last edited on
It works that way because that's how C++ ensures that types match. You can downcast your tertiaryobj to a secondaryobj when you call somefunction(). Or, you can make somefunction a template function.
Ah seems kind of unecessarily restrictive to me but thanks i'll look into down casting and template functions!:)
Your code compiles and runs fine for me (Visual Studio 2008). And technically, this is not down casting as casting from tertiaryobj to secondaryobj is going up the inheritance chain. In this case, it's an up cast and you should be able to cast from an object to its parent object without problems.

If you do this:

somefunction(obj1, (secondaryobj*) obj3);

does the code compile for you?
Thanks shacktar: I was thinking about fishing, not C++ ...
Yes thank you shacktar. I'm glad i checked back. It didn't compile in codeblocks.
Topic archived. No new replies allowed.