Is there anyway to declare an object of a class before the class is created in C++? I ask because I am trying to use two classes, the first needs to have an instance of the sec
There's an elegant solution using templates.
template< int T > class BaseTemplate {}; typedef BaseTemplate< 0 > A; typedef BaseTemplate< 1 > B; // A template<> class BaseTemplate< 0 > { public: BaseTemplate() {} // A constructor B getB(); } // B template<> class BaseTemplate< 1 > { public: BaseTemplate() {} // B constructor A getA(); } inline B A::getB() { return A(); } inline A B::getA() { return B(); }
This code will work! So, why does it work? The reason has to do with how templates are compiled. Templates delay the creation of function signatures until you actually use the template somewhere. This means that neither getA() nor getB() will have their signatures analyzed until after both classes A and B have already been fully declared. That's the magic of this method.