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?

Answers


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" ); 
  }
}

Need Your Help

Restarting a Java Program Within Eclipse

java eclipse restart

I own a game server and I was just wondering, instead of running the server in eclipse and then when I restart it, it opens a new cmd prompt outside of eclipse and runs the server on that. Could I ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.