Hello everyone,
I've two class A and B,
in head file :
=========================
class A{
// A will use type BPtr
}
class B{
// B will use type APtr
}
typedef shared_ptr<A> APtr
typedef shared_ptr<B> BPtr
=========================
Could anyone give me some advices to deal with this scope problem,
thank you in advance.
Jun
=========================
Jun:
Might I suggest something to you about the above code. You can fix
this by forward references, but you are going to have a problem with
cyclic dependency here that you probably should get used to
identifying and eliminating. Cyclic dependencies cause all types of
headaches in software development and it's best to be able to identify
them and eliminate them. One way is to use dependency inversion or
basically create pure interfaces for your classes that the other one
depends on rather than making it directly dependent on the other
class. So in your case:
class IA // pure virtual interface of A
{
....
};
class IB // pure virtual interface of B
{
....
};
typedef shared_ptr<IA> APtr
typedef shared_ptr<IB> BPtr
class A : public IA
{
// A will use type BPtr
};
class B : public IB
{
// B will use type APtr
};
There are 2 potential reasons not to use this - the interfaces
introduce virtual calls which should only impact you if you are in an
exteremly performance critical area, and the pain of having to update
2 class interfaces when you add a method. After being in the software
industry for a while, the first reason is almost always used as an
excuse for the second. 95% of the time neither are an issue.
Cheers!
Madhacker