I am relatively new to C++ and I have been working on a basic 3D rendering engine using OpenGL.I have the following issue:
I have a class called GeomEntity which is the base class for all geometry primitives.I have another class called DefaultMaterial which is the base class for all materials(consists of different types of shader programs) .Because I am going to have many types of materials like :ColorMaterial,TextureMaterial,AnimatedMaterial and so on I need to put a reference to the material in GeomEntity class so that from the main app I can set any of the material with this function:
void GeomEntity ::addMaterial (const DefaultMaterial *mat){
material=mat;////material is the member variable pointer of type DefaultMaterial
}
But the thing is that although all of those materials are derived from the DefaultMaterial they all have got their unique methods which I can’t trigger if I reference them to the variable of DefaultMaterial by default.
So for example in the main application:
Sphere sphere;
....
sphere.addMaterial(&animMaterial);///of type AnimatedMaterial
sphere.material->interpolateColor(timerSinceStart);
///doesn't happen anything as the sphere.material is
/// of type DefaultMaterial that has no interpolateColor() method
I know I have can use templates or casts but I would like to hear about the best practices of this kind of polymorphism in C++ .In Java or C# I would really use something like this:
((AnimatedMaterial)sphere.material).interpolateColor(timerSinceStart);
In C++ you can do this using dynamic_cast, that is I believe closest equivalent of that C# feature: