Flexible arrays of pointers
What I want to do is this:
CClass { };
CAClass : public CClass { };
CBClass : public CClass { };
CClass *ary;
ary = new CClass[100];
ary[x] = new CAClass; // or what ever.
In other words, I want an array that can hold a class and any class that inherits from it. Can I use STL for this, and if so, how?
Thanks.
I want this for a mesh class. A mesh could be animated in very different ways but each one would still call Render() or SetAnimation() or Load().
It seems to me that what you want is not what you typed. In your version, you have an array of CClass objects ; however, to enable polymorphism, you need pointers to objects:
CClass **ary;
ary = new CClass*[100];
ary[x] = new CAClass; // or what ever.
With the STL, this would be easily achieved by creating a vector of pointers.
[edited by - Miserable on January 19, 2003 9:26:56 AM]
CClass **ary;
ary = new CClass*[100];
ary[x] = new CAClass; // or what ever.
With the STL, this would be easily achieved by creating a vector of pointers.
std::vector<CClass*> vec;for(int i = 0; i < SOME_LIMIT; i++) vec.push_back(new CAClass); // or whatever, as you put it// More code ...// Just remember, if you push_back new elements, to delete themfor(int i = 0; i < vec.size(); i++) delete vec[i];vec.clear();
[edited by - Miserable on January 19, 2003 9:26:56 AM]
The only mistake you have made is in the way you have initialised CClass *ary.
Do this..
then when you create a new object of type A or B do this..
or this..
then..
will call the derived render function. Note, Render() must be declared as a virtual member function in CClass.
If you want to use stl instead of a fixed number of meshes, do this..
To create a new mesh..
Then to loop through the meshes (the easy way)
Easy hey?
- Matt
Help me!
[edited by - matibee on January 19, 2003 9:29:10 AM]
Do this..
CClass * ary[100]; // 100 pointers to CClass
then when you create a new object of type A or B do this..
ary[x] = new CAClass;
or this..
ary[x] = new CBClass;
then..
ary[x]->Render();
will call the derived render function. Note, Render() must be declared as a virtual member function in CClass.
If you want to use stl instead of a fixed number of meshes, do this..
std::vector< CClass * > vecMeshes;
To create a new mesh..
vecMeshes.push_back( new CAClass() ); // or CBClass
Then to loop through the meshes (the easy way)
for (int t= 0; t < vecMeshes.size(); t++)vecMeshes[t]->Render();
Easy hey?
- Matt
Help me!
[edited by - matibee on January 19, 2003 9:29:10 AM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement