Common C ++ Objects
I have four classes A
, B
, C
and D
.
- The class
A
has a member of theB
classB
. - The class
B
has a member of theC
classC
.
A
has a member D* dpointer;
This hierarchy must be preserved (in fact it is a GUI with a window, a window, a panel like A
, B
and C
).
Now B and C should use the method from *dpointer
.
Is there anything more elegant than providing dpointer
as a member B
and C
? This is bad?
a source to share
In this situation, most likely, instead of a pointer, you should pass a reference to B
and C
. As @Billy ONeil says in his answer , you should use shared_ptr
or scoped_ptr
, if possible and appropriate (can't judge without knowing more about D
and dpointer
) in A
. Passing a reference to B
and C
has the advantage that it is clear that the two are just using the
D
-object, but do not manage its lifecycle, and that an instance D
(with a pointer NULL
) is required to use these classes . If B
u C
only call methods const
on D
, you can even pass a const reference.
a source to share
struct D;
struct CommonABC
{
CommonABC(D * & dpointer) : dpointer(dpointer) {}
D * & dpointer;
};
struct C : CommonABC
{
C (const CommonABC & common) : CommonABC(ommon) {}
};
struct B: CommonABC
{
B (const CommonABC & common) : CommonABC(ommon), c(common) {}
C c;
};
struct A
{
A () : b(CommonABC(dpointer)) {}
D * dpointer;
B b;
};
a source to share
In practice, I would choose the shared_ptr solution mentioned above. But here's another way that isn't often seen in the C ++ literature, of the kind you might find in an interview or in the BrainBench test:
struct D{
D(int val);
void foo();
};
struct C:private virtual D{
void bar(){
foo();
}
};
struct B:private C,private virtual D{
void car(){
foo();
}
};
struct A:private B,private virtual D{
A(int val):D(val){}
void aar(){
car();
foo();
}
};
personal inheritance implements a has-a relationship, just as it does a member. The only difference is that you can only have one type. In this case, the same D object is shared by all classes in the composition.
But if you want others to be able to understand what you are doing, move on to shared_ptrs.
a source to share