C++ Best Practices – Defining Constants Using Class Static Methods

cconstants

Instead of using #define or const, I usually define constants using class static methods as follows:

//AppConstants.h
#include <string>
class AppConstants{
public:
    static int getMax();
    static std::string getPrefix();
};

//AppConstants.cpp
#include "AppConstants.h"
int AppConstants::getMax(){
    return 30;
}

std::string AppConstants::getPrefix(){
    return "myprefix";
}

I do this usually when creating a mobile app, which I would like to save the compile time when each time change the value for testing. Is it a bad practice?

Best Answer

Yes, and it's unnecessary too. You can declare constants in headers and define them in source files just like functions:

class AppConstants {
public:
  static const int Max;
  static const std::string Prefix;
};

const int AppConstants::Max = 30;
const std::string AppConstants::Prefix = "myprefix";

Especially in the case of the string, this has the advantage of not constructing a new one every time you access it.

It also has the disadvantage of being affected by C++'s unspecified global initialization order, so be careful if you use the constants from the initialization of other global variables/constants.