1

I have a c++ project which has multiple cpp files and functions.

Each file needs its own parameters (i.e., MaxHorizonVelocity, MaxVerticalVelocity etc.).

I want that these parameters won't be hard coded but read from a single configuration-parameters file at an initialization step.

For now I think to define a parameters class which will read the parameters at the begining and will be "static" (in some sense which I'm not sure about ...).

Is that considered a good practice? Is there another way?

Benny K
  • 1,957
  • 18
  • 33
  • 1
    Having a single class/object responsible for the configuration variables (be it from a file or from command-line arguments or other source) is in fact common practice. I recommend you look into e.g. the [Boost property tree](http://www.boost.org/doc/libs/1_59_0/doc/html/property_tree.html) or [Boost program options](http://www.boost.org/doc/libs/1_59_0/doc/html/program_options.html) libraries instead of making up your own system. – Some programmer dude Oct 28 '15 at 06:10
  • Do you mean constant rather than static? If do, you can define const attributes that can only be initialized at instantiation of a class. See http://stackoverflow.com/questions/14495536/how-to-initialize-const-member-variable-in-a-class-c for a question on how to do this. – Harald Oct 28 '15 at 06:12
  • It's an OK direction. Try it and ask questions if it doesn't work for you. – n. m. could be an AI Oct 28 '15 at 06:14

1 Answers1

2

I usually handle this problem in below way. The code itself is self-explanatory.

All configurable items must be derived from IConfigurable interface.

class IConfigurable {
    public:
        virtual void configure(XMLNode&) = 0;
};

Each configurable item assumes that configure function will be called and given XMLNode will be the root node in configuration xml file. After that each configurable item does specific parsing according to itself.

class CommandClick : public IConfigurable {
    public:
        void configure(XMLNode& xCommandNode) {
            XMLNode xClickCoordinate = xCommandNode.getChildNode("Coordinate");
            unsigned int x = atoi(xClickCoordinate.getAttribute("x"));
            unsigned int y = atoi(xClickCoordinate.getAttribute("y"));
            mClickCoordinate.setX(x);
            mClickCoordinate.setY(y);
        }
    private:
        Coordinate mClickCoordinate;
};
Validus Oculus
  • 2,756
  • 1
  • 25
  • 34