I’m trying to make a class inherits from other and override some methods. Classes ‘header’ is:
class Objeto {
public:
virtual bool interseca(const Rayo &rayo, float magnitud);
virtual bool breakNormal(const Punto &punto);
virtual Vector normal(const Punto &punto);
int idMaterial;
};
class Esfera: public Objeto {
public:
int idMaterial;
virtual bool interseca(const Rayo &rayo, float magnitud);
// etc
};
Next in other place of the program (outside of Objeto and Esfera) I do:
// ObjectList is a Vector<Objeto>
Objeto o = esfera; /* Where esfera is a valid Esfera object */
ObjectList[0] = o;
ObjectList[0].interseca(rayo, magnitud);
What I want is to call the new version of interseca that is in Esfera. In this way I can add more objects (Cube, Triangle, etc) and treat them as generic “Objetos”.
But instead of the Esfera implementation of interseca the program calls Objeto::interseca.
What is the correct way to do this override with C++? Is that the way to do overriding and I’m missing something or I’m plain wrong? Any tip or alternative to do that?
You can only get polymorphic behavior if you access the class via a pointer or reference. In addition to that, you are slicing the object when you are copying the derived type to a non-pointer/non-reference base type.
Slicing:
http://en.wikipedia.org/wiki/Object_slicing
Given these definitions:
This won’t do what you want:
But this will:
Program design
A technique you can use to avoid this in the future is to make your base classes (pure) abstract.
Would you ever instantiate a true
Objetoin your scene, or are you simply defining a base type? If you are just defining a base type (which I recommend), then you can makeinterseca,breakNormal, andnormalpure virtual. Then, the compiler will catch problems like the one you have here.Then, this will be okay:
But this will cause the compiler to error – a good thing, cause it’s catching a bug: