I have got four classes A, B, C and D.
- Class
Ahas a memberbof class
B. - Class
Bhas a membercof classC.
A has a member D* dpointer;
This hierarchy has to be preserved (in fact this is a GUI with app, window, panel as A, B and C).
Now B and C must use a method from *dpointer.
Is there something more elegant than giving dpointer as a member of B and C ? Is it bad ?
In this situation you should probably pass a reference to
BandCinstead of a pointer. As @Billy ONeil says in his answer, you should use ashared_ptror ascoped_ptrif possible and appropriate (cannot judge without knowing more aboutDanddpointer) inA.Passing a reference to
BandChas the advantage of making clear that these two merely usethe
D-object, but do not control it’s lifecycle, and that an instance ofDis required to use these classes (with a pointerNULLwould be an option). IfBandConly callconstmethods onD, you can even pass a const reference.