Search code examples
c++static-membersforward-declaration

forward declaration of a class having static member


Am I doing anything wrong in below code. I am getting the following compilation error :

ERROR: Invalid use of incomplete type classSample

But I have already forward declared the class Sample.

class Sample;

int Sample::objCount = 0;

class Sample
{
public:
    static int objCount;
    Sample()
    {
        Sample::objCount++;
        std::cout<< "creating object = "<<Sample::objCount<<std::endl;
    }
    ~Sample()
    {
        Sample::objCount--;
        std::cout<< "destroying object = "<<Sample::objCount<<std::endl;
    }
};

int main()
{    
    Sample obj;
    return 0;
}

Solution

  • Forward-declaring a class is a promise to the compiler to provide a definition at some later point. In return the compiler lets you use your forward-declared class in other declarations, where the content of the class is not required, such as declaring a pointer or a reference.

    Defining members of a class relies on the knowledge of the content of the class. Therefore, a simple forward declaration is no longer sufficient: your class must be defined in order for the compiler to deal with its member definitions properly.

    In your example forward declaration is not required. You should move class definition into a header file, include it in your main file, and move Sample::objCount either into the main file, or into a separate sample.cpp file.