Friday, February 1, 2008

Forward Declarations

From time to time we need to declare a class earlier than its definition. Consider the following example. To be able to define Object class I need to first declare String, otherwise the compiler will complain about the method that returns String.

//I need forward declaration here
class String;

class
Object
{

public
:
//toString return a String object
String toString();
};


//Now the definition comes
class String : public Object
{

};
What about forward declaration of a template class?

template <typename T>
class
SmartPtr;

class
Object
{

public
:
SmartPtr<Object> clone();
};


//Now the definition comes
template <typename T>
class
SmartPtr : public Object
{

};




No comments: