C++ store any child struct/class in array? -


in c++ have series of structures defined...

struct component {}; struct scenegraphnode : component {}; struct renderable : component {}; struct health : component {}; 

these classes, i've been told there little difference in c++.

in java possible declare array of type component , put class extends (inherits) component it. java considers them components , since uses smart pointers, java's "array" list of smart-pointers same size.

however understand java handles arrays different c++. when checked size of each of these structs got following.

component                   // 4 scenegraphnode : component  // 8 renderable : component      // 8 health : component          // 20 

which isn't suprising. when create array of components, size of blocks going 4 (bytes) won't hold of other structures.

so question is, how can store loose list of components (ie list can store class / struct inherits component)? in java mind-numbingly simple do. surely there must easy way in c++ it.

you allowed have base class pointer child class object, ie component * sgn = new scenegraphnode

so allocate array of component*s (or vector if needs vary in size) , make each entry point derived object.

component * components[100]; components[0] = new scenegraphnode; components[1] = new renderable; // on , on 

in addition must have virtual functions in component member function intend define in child classes

class component {     public:         virtual void method() = 0;         virtual int method2(int arg) = 0; };  class scenegraphnode : public component {     public:         virtual void method(){             //body         }         virtual int method2(int arg){             return arg*2;         } }; 

the virtual keyword makes @ runtime looks @ actual type of pointed object , calls method, rather calling pointer types method. how java things normally. = 0 makes function "pure virtual" meaning child class must define method. using our array defined above...

components[0]->method(); compenents[2]->method2(1); 

if prefer vector array, can replace array version with:

#include <vector>; //... std::vector<component* > components; components.push_back(new scenegraphnode); components.push_back(new renderable); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -