"Incomplete type not allowed " when creating std::ofstream objects

arun49 vs picture arun49 vs · Mar 5, 2015 · Viewed 35.8k times · Source

Visual Studio Throws this Strange Error:

Incomplete type not allowed

When I try to create an std::ofstream object. Here is the code I wrote inside a function.

void OutPutLog()
{
     std::ofstream outFile("Log.txt");
}

whenever it encounters this Visual Studio throws that Error. Why This Happens?

Answer

As @Mgetz says, you probably forgot to #include <fstream>.

The reason you didn't get a not declared error and instead this incomplete type not allowed error has to do with what happens when there is a type that has been "forward declared", but not yet fully defined.

Look at this example:

#include <iostream>

struct Foo; // "forward declaration" for a struct type

void OutputFoo(Foo & foo); // another "forward declaration", for a function

void OutputFooPointer(Foo * fooPointer) {
    // fooPointer->bar is unknown at this point...
    // we can still pass it by reference (not by value)
    OutputFoo(*fooPointer);
}

struct Foo { // actual definition of Foo
    int bar;
    Foo () : bar (10) {} 
};

void OutputFoo(Foo & foo) {
    // we can mention foo.bar here because it's after the actual definition
    std::cout << foo.bar;
}

int main() {
    Foo foo; // we can also instantiate after the definition (of course)
    OutputFooPointer(&foo);
}

Notice we could not actually instantiate a Foo object or refer its contents until after the real definition. When we only have the forward declaration available, we may only talk about it by pointer or reference.

What is likely happening is you included some iostream header that had forward-declared std::ofstream in a similar way. But the actual definition of std::ofstream is in the <fstream> header.


(Note: In the future be sure to provide a Minimal, Complete, Verifiable Example instead of just one function out of your code. You should supply a complete program that demonstrates the problem. This would have been better, for instance:

#include <iostream>

int main() {
    std::ofstream outFile("Log.txt");
}

...also, "Output" is generally seen as one complete word, not two as "OutPut")