Communication between objects in C++ -
i have 2 classes , b defines follows:
class { public: void *connector; }; class b { public: void *connector1; void *connector2; };
to start, let assume create 3 objects c1, c2 , c3 based on these classes,
a c1; b c2; c3;
and use following code connect them
c1.connector = &c2; c2.connector1 = &c1; c2.connector2 = &c3; c3.connector = &c2;
so @ moment have this: c1 <-> c2 <-> c3 (first example).
important: reason using void pointers inside classes because cannot predict right start how objects connect. example,the answer question should valid if create fourth object , make these connections (c1 , c2 same before):
b c3; c4; c1.connector = &c2; c2.connector1 = &c1; c2.connector2 = &c3; c3.connector1 = &c2; c3.connector2 = &c4; c4.connector = &c3;
which corresponds c1 <-> c2 <-> c3 <-> c4 (second example).
i tried , searched everywhere simple solution implement communication between these objects. there several questions same name not find similarity between asked , respective answers problem trying solve. maybe because not approaching correctly right start. anyway, communication mean simple way c2 can call method in c1 , vice versa.
1) tried templates not figure out how it. classes templates , seamed contrived , complicated (hard read, maintain , implement).
2) tried use casting of pointers since don't know right form start class connect not it.
important: although cannot warranty connections can live fact that, example, object of class b knows name of method execute in object connected connectors.
to make clear, let assume introduce method
int get_value();
in both class , class b (but implementation different in each class). so, in second example above, c2 may call on c1 , c3 may call method on c2. note c2 , c3 objects of same class.
ok, explained problem, ask simple solution communication in problem. example, working piece of code implements communication between c2 , c1 between c3 , c2 (see example 2 above).
to specific think example in object c2/c3 can call get_value method in c1/c2, such c2/c3 can store value in private/public variable perfect.
i realize way trying implement may not best , answers solve problem on different approach welcome. if possible please show me code , little explanation because main target , expertise not programming skills.
thank in advance.
basically, void* isn't way go.
one alternative approach use inhertiance:
class obj { public: virtual string getvalue()=0; }; class : public obj { public: obj *connector; string getvalue(); }; class b : public obj { public: obj *connector1; obj *connector2; string getvalue(); };
the objects "communicate" refering common members of base obj class.
c1.connector->getvalue(); c1.connector->connector2->getvalue();
Comments
Post a Comment