'file' has incomplete type...How to...

Started by
3 comments, last by Samsonite 17 years, 8 months ago
Hello, and thanks for reading! I have this class CLogger. It has two variables which is: "std::string filename" and "std::ofstream file". I also have two methods, which is: "virtual void OpenLogFile()" and "virtual bool WriteToFile(std::string)". In my method "OpenLogFile()" I need to access the member variable "file", and then later, in my method "WriteToFile(std::string)" I need to access that variable once again because I'm writing to it. The thing is, I get an error saying:

'file' is incomplete type


Here's the code: CLogger.h

#ifndef CLOGGER_H
#define CLOGGER_H

class CLogger //Logger class
{
      public:
             //variables
             std::string filename; //Filename of the log file
             std::ofstream file; //file object
             
             
             //methods
             virtual void OpenLogFile(); //This is called at the start...
             
             virtual bool WriteToFile(std::string); //Writes a string to a file
             
};


#endif 


CLogger.cpp

#include <iostream>
#include <fstream>
#include "CLogger.h"

void CLogger::OpenLogFile()
{
          file.open(this->filename.c_str(), std::ios::app); //Open file for writing
}

bool CLogger::WriteToFile(std::string text) //WriteToFile method, writes the string to the file
{
     if(file.is_open()) //If the file is opened
     {
             //Write to file
             file << text << "\n";
     }
     else //if the file is not opened
     {
          file.close(); //close the file
          return false; //return failure
     }
     file.close(); //Close the file
     return true; //Writing succeded, return success.
}
          


main.cpp

#include <iostream>
#include "CLogger.h"

CLogger* Logger = new CLogger();//Create a new log object 



int main()
{
    Logger->filename = "log.txt";//Set the logfile's name to "log.txt"
    Logger->OpenLogFile(); //open the logfile for writing
    Logger->WriteToFile("Starting log file..."); //write to file
    Logger->WriteToFile("Hello world"); //Write "hello world" to the file
}


Thanks for any help! [smile]
Hope I was helpful. And thank you if you were!
Advertisement
In main.cpp or CLogger.h you need to #include <fstream>.
Cool, adding "#include <fstream>" to main.cpp fixed it. But why does main.cpp need to know about the ofstream object?
Hope I was helpful. And thank you if you were!
If it doesn't have the definition of the complete type, it can't generate the default construtor necessary for creating a new object, or know the right size of memory it needs to allocate when calling new.
Got it! Thanks alot!
Hope I was helpful. And thank you if you were!

This topic is closed to new replies.

Advertisement