Archived

This topic is now archived and is closed to further replies.

Drath

Flexible arrays of pointers

Recommended Posts

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.

Share this post


Link to post
Share on other sites
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.


    
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 them

for(int i = 0; i < vec.size(); i++)
delete vec[i];
vec.clear();


[edited by - Miserable on January 19, 2003 9:26:56 AM]

Share this post


Link to post
Share on other sites
The only mistake you have made is in the way you have initialised CClass *ary.

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]

Share this post


Link to post
Share on other sites