In this particular case, CMediaType
extends AM_MEDIA_TYPE
directly, so the cast will work just fine. (You're talking about the DirectShow classes, are you?) You can always cast subclasses to their base classes safely, that's why it'll work.
Here's a simple class structure with inheritance:
public class Animal {
public abstract String makeSound();
public void move(...) {
...
}
}
public class Lion extends Animal {
public String makeSound() {
return "GRRRRRR";
}
public void yawn() {
...
}
}
You could instantiate a lion like this and then cast it to an Animal safely:
Lion lion = new Lion();
Animal animal = (Animal) lion; //Perfectly legal
animal.move();
animal.makeSound();
By extending Animal
(or inheriting from Animal
, as it's also called), the Lion
class states that it is also an animal (they have a is-a-relationship), therefore, it's safe to cast a lion to an animal and assume it has all the properties and methods defined in the Animal
class.
Casting a base class to a subclass, however, will not usually work:
Animal animal = getAnimalFromSomeWhere();
Lion lion = (Lion) animal;
lion.yawn();
This can't work, as not every animal is a lion. Depending on the language, you'll either get type cast errors or just undefined behaviour at runtime.
There's an exception: If you know for certain the object you have is of a particular subclass, you can do the cast anyway. So in if animal in fact is a Lion
, this'll work just fine:
Animal animal = getAnimalFromSomeWhere();
Lion lion = (Lion) animal; //works if animal is lion, fails otherwise
lion.yawn();
Most languages offer type checks at runtime ("Is this animal a lion?"), I don't know how that would look in C++, though, so another Java-ish example:
if (animal instanceof Lion) {
Lion lion = (Lion) animal; //safe
}