Search code examples
c++fileiostaticinitialization

Can I read a file(.txt) in static object? C++


I have an static object. File reading code is placed in that object's constructor. Is this right or correct code? Do this code have any problems?

A.hpp

Class A
{
public:
    A();

private:
    static A someA;
}

A.cpp

A A:someA;

A:A()
{
    ofstream myfile;
    myfile.open ("example.txt");
}

Solution

  • Allmost using static is a bad thing. If you must have something that is permanent in your apps you should use the "singleton" design pattern.

    Having a reference of some class in himself should be made with a pointer and is use for example in a chained list.

    For standard use of class you do this after the description of your class

    int  main( int argc, char**argv )
         {
           A Myclass           (   ) ;
           MyClass.DoSomething (   ) ;
           return              ( 0 ) ;
         }