Search code examples
c++fileinitializationifstream

How to initialize an object that declared as const on header file?


I want to initialize std::ifstream object only in the main() function after declare it in the header.

Is there any way to do it in C++?

I wrote this but it's not compiling

//header.h
#include <iostream>
#include <fstream>

class class1{
        static const std::ifstream fs;
};

//proj.cpp
#include "header.h"

void main(){
        class1::fs("Employee.txt")
}

Solution

  • static variables need to be defined at global scope, not inside a function.

    main should also return int not void.

    A const std::ifstream doesn't make much sense as most of the methods you would need to use are non-const so wouldn't be callable on your const stream.

    Fixing these issues gives:

    //header.h
    #include <iostream>
    #include <fstream>
    
    class class1{
            static std::ifstream fs;
    };
    
    //proj.cpp
    std::ifstream class1::fs("Employee.txt");
    int main(){
        return 0;
    }
    

    If you want to open the stream in main then you need to do:

    const std::ifstream class1::fs;
    int main(){
        class1::fs.open("Employee.txt");
        return 0;
    }