Search code examples
c++inheritanceradixderived

Acessing derived members from vector of base type


Say I have some situation like this:

class Vertex
{
public:
    Position position;
    Normal   normal;
    Texcoord texcoord;
    int      boneID;
};

class VertexSkinned: public Vertex
{
public:
    float boneWeights[3];
    int   boneIDs[3];
};

class VertexMorphed: public Vertex
{
public:
    Position posTargets[3];
    Normal   normTargets[3];
    Texcoord texcoordTargets[3];
};

std::vector<Vertex> vertices;

VertexSkinned vs;
VertexMorphed vm;
Vertex        v;

vertices.push_back( vs );
vertices.push_back( vm );
vertices.push_back( v );

// This is illegal right? But how would I go about achieving the desired effect
float someFloat = vertices.front().boneWeights[2];

The question is in the comment. I rarely ever use inheritance and thought I might have found a beneficial use here, although it doesn't seem to be possible.

I assume using a vector of pointers and then dynamic casting to the derived class works? This isn't what I want to do though.


Solution

  • I don't see any other option other than storing the pointers and dynamic_cast later to get the derived object. If you want to do something like, can't you have 3 different vectors each with its own type. In that case, there is no need of the pointer business.