Rodolfo
Rodolfo

Reputation: 119

How to fill objects with many different member types in a clever way, polymorphically?

Is there an OO pattern to fill objects with lots of data, with this data being usually different within each object, polymorphically? [edited] The issue here is that in another part of the code I will have a pointer to the base class and I want to fill the data of the concrete objects pointed by this base class.

Example:

public Filler
{
     virtual void fill_struct1(struct myStruct1) = 0;
     virtual void fill_struct2(struct myStruct2) = 0;
     // I will need more methods to give the derivate objects the capacity of
     // filling its data members polymorphically.
}

class A: public Filler
{
     void fill_struct1(struct myStruct1);
     void fill_struct2(struct myStruct2);
     // There can be more overwritten methods.
     struct myStruct1 member_1;
     struct myStruct2 member_2;
     struct myStruct3 member_3;
     // There can be more members of different types.
}

class B: public Filler
{
     void fill_struct1(struct myStruct1);
     void fill_struct2(struct myStruct2);
     void fill_struct4(struct myStruct4);
     // There can be more overwritten methods.
     struct myStruct1 member_1;
     struct myStruct2 member_2;
     struct myStruct4 member_3;
     // There can be more members of different types. But sometimes the members can be equal one used in a sibling.
}

Upvotes: 0

Views: 106

Answers (2)

lubgr
lubgr

Reputation: 38267

Try to separate concerns here:

  • Setting up instances of A or related classes should be done in the constructor. If you have too many parameters to be passed into the constructor, group them in a struct.
  • If setting up different instances requires similar code snippets, put these in a free function
  • If the logic behind setting up these instances is very complicated, look out for the builder pattern. This involves classes in a different hierarchy, opposed to what your current approach suggests.
  • Base classes and derived classes can have different member variables, it's fine to separate them as much as possible. Share state between derived classes via protected member variables in the base class only when necessary.

Another issue is quite orthogonal to this first point:

  • The concrete type of your subclasses are known when instantiating them: simply invoke the constructor
  • The concrete type shall be hidden. You instantiate via a clone-like method (virtual constructor idiom, prototype pattern).

Upvotes: 1

Max Langhof
Max Langhof

Reputation: 23681

One way to beat some redundancy could be to use template methods:

template<class T>
void fill_struct1(T& obj)
{
  obj.member_1 = ...;
}

This can be called on any object that has a member_1 (with type myStruct1, presumably). If all your fill_struct1 methods do the exact same thing, this may be worth looking into.

Upvotes: 1

Related Questions