c++ - Multiple constructors in a class -
i have class a,b,c,d have member of class x in it. have class called class p.
in class create instance of class p well. in class p need access x instance of , method of (this method available in class b,c,d same method signature , parameters), therefore pass class class p while initializing class p.
so code looks like;
class p; class a{ public: x x; p *p; a(){ x = new x(); }; void setdata(){ p = new p(this); } }; class p{ public: *a; p(a *_a){ = _a; a->x.resetval(); } };
now need create instances of p in class b,c,d , pass instances of classes p.
to knowledge achieve must either make a,b,c,d child class of new class (class parent) , set constructor of class p accept class parent instance, or must create separate constructors classes a,b,c,d in class p.
class parent { x x; } class p; class a:: parent{ ...........//code }; class p{ public: parent *prnt; impl(parent *prnt){ .........//code } }; ---------------------- or ------------------------- class p{ public: *a; b *a; c *a; d *a; impl(a *_a){ .............//code } impl(b *_b){ .............//code } impl(c *_c){ .............//code } .............//code };
i not want change class a,b,c,d because complicated classes not written me. there way achieve other 2 above methods?
any appreciated. thanks.
if need access x instance in each of classes, can pass pointer x instance constructor of p.
class p { public: x* x; p(x* _x) { x = _x; // code } }; class a{ public: x x; p *p; a(){ x = new x(); }; void setdata(){ p = new p(x); } };
Comments
Post a Comment