I understand that only default constructors can be used to instantiate arrays.
I'm working on a project that is using a third party piece of GUI software. The GUI objects do not seem to have default constructors. Adding them to arrays would make my code much more maintainable.
I'm hoping someone knows of a work around for me, or that I'm conceptually misunderstanding this. For instance, is there a way to inherit from the GUI object's class and add a default constructor? Maybe have the derived class simply hold an object of the base class instead of actually inheriting it?
Thank you.
(note: I do not have access to std namespace on this project)
If you inherit, you *could* make a default constructor that simply calls the GUI object's constructor with arguments you need. Might look kind of weird though.
You could also do it like you said, and just contain and instance of the GUI object which is initialized in your class's initializer list.
struct Obj {
Obj( int ) {} // ie, no default constructor
};
// Make a container of 100 instances of Obj constructed with 42:
std::vector<Obj> v( 100, Obj( 42 ) );
Using an STL container, as suggested by jsmith, is surely the easiest way.
You could also construct them individually by pushing each instance into the vector.
Extending jsmiths example:
1 2
v.push_back( Obj(10) );
v.push_back( Obj(25) );// and so on...
Using an array of pointers as suggested by firedraco would allow individual instantiation also:
1 2 3 4 5
Obj* p_obj[3];// for an array of 3 for example
// then allocate to each pointer using new
p_obj[0] = new Obj(10);
p_obj[1] = new Obj(15);
p_obj[2] = new Obj(20);
You would need to delete these objects when you are finished with them:
1 2 3
for(int i=0; i<3; ++i)
delete p_obj[i];
However, you CAN instantiate a regular array using constructors other than the default one:
Obj obj_array[] = { Obj(10), Obj(15), Obj(20) };// create an array of 3 Obj objects.