Huy Pham
Huy Pham

Reputation: 493

static const member initialization from file

How do you initialize a static const member with a value that is stored in a file? For example:

Class Foo
{
private:
  static const String DataFromFile;
  void InitData (void);
};

I know for a short value, I can initialize with:

const String DataFromFile = "Some Value";

But what if the value is really a "big" value and encrypted and stored in a disk file? I need to decrypt it before putting it into DataFromFile.

Is there a way to do it or can I just forget it and treat it as a regular variable? That is, instead of:

static const String DataFromFile;

can I just declare it as:

String DataFromFile;

and initialize it with a function?

Upvotes: 2

Views: 775

Answers (1)

Werner Erasmus
Werner Erasmus

Reputation: 4076

How do you initialize a static const member with a value that is stored in a file? For example:

Like this:

//X.h
#include <string>
class X
{
  //...
  static const std::string cFILE_TEXT_;
  static const bool cINIT_ERROR_;
};

//X.cpp
//...#include etc...
#include <fstream>
#include <stdexcept>

namespace {    
std::string getTextFromFile( const std::string& fileNamePath )
{
  std::string fileContents;
  std::ifstream myFile( fileNamePath.c_str() );
  if( !(myFile >> fileContents) );
  {
    return std::string();
  }
  return fileContents;
}
}

const std::string X::cFILE_TEXT_( getTextFromFile( "MyPath/MyFile.txt" ) );
const bool X::cINIT_ERROR_( cFILE_TEXT_.empty() );

X::X()
{ 
  if( cINIT_ERROR_ )
  { 
   throw std::runtime_error( "xxx" ); 
  }
}

Upvotes: 5

Related Questions