Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ constructor: Initialize local variable before initializer list

Tags:

c++

How to store temporary state, needed for the initializer list, in the constructor (on the stack)?

For example, implementing this constructor …

// configabstraction.h
#include <istream>

class ConfigAbstraction
{
public:
    ConfigAbstraction(std::istream& input);

private:
    int m_x;
    int m_y;
    int m_z;
};

… using a stateful helper class like this?

// mysillyparserdontworry.h
#include <json/reader.h> //jsoncpp

class MySillyParserDontWorry
{
public:
    MySillyParserDontWorry(std::istream& input) { input >> m_parseTree; }
    int intByName(const char* name) const { return m_parseTree[name].asInt(); }

private:
    Json::Value m_parseTree;
};

My attempt:

// configabstraction.cpp

ConfigAbstraction::ConfigAbstraction(std::istream& input)
    : local_parserState(input) // init local variable first: Not possible!
    , m_a(local_parserState.intByName("a"))
    , m_b(local_parserState.intByName("b"))
    , m_c(local_parserState.intByName("c"))
{
    MySillyParserDontWorry local_parserState; // ...because it is local
}
like image 582
user2394284 Avatar asked Nov 02 '15 17:11

user2394284


1 Answers

With C++11 you could solve this with delegating constructors:

class ConfigAbstraction
{
public:
    ConfigAbstraction(std::istream& input);

private:
    ConfigAbstraction(const MySillyParserDontWorry& parser);

    int m_a;
    int m_b;
    int m_c;
};

ConfigAbstraction::ConfigAbstraction(const MySillyParserDontWorry& parser)
    : m_a{parser.intByName("a")}
    , m_b{parser.intByName("b")}
    , m_c{parser.intByName("c")}
{
}

ConfigAbstraction::ConfigAbstraction(std::istream& input)
    : ConfigAbstraction{MySillyParserDontWorry{input}}
{
}
like image 118
mattnewport Avatar answered Sep 21 '22 10:09

mattnewport