vendredi 14 décembre 2018

Constructor delegation and const inititialization [c++11]

I'm using constructor delegation on this structure :

class C
{/*DATA TO INITIALIZE*/};

class A
{
protected:
    std::vector <C> currentConf;
    static const std::vector <C> defaultConf;
    static const std::string name;
    /*other members*/

    A(const std::string &n):
        name(n),/*other members initialization*/{}
public:
    static const std::vector<C>& getDefault(){return defaultConf;}
};

class B final : public A
{
private:
    /*SomeHow initialize static member*/
public:

    B():A("NameB"){ 
        currentConf=defaultConf;}
};

expected behaviour : when B::getDefault() is called, I should have B's default configuration, properly initialized. each class that inherits from A should declare a method, or at least the list of parameters to initialize the defaultConf "A" should not be instantiable and A::getDefault() should be impossible.

I first thought of making a virtual static method but this is impossible in C++ so far Obviously I will have D and E classes that will inherit from A, and have their own defaultConfig

I also tried a virtual method such as :

virtual const std::vector<C>& defaultC(){
    static const C c1(/*DATA*/);
    /*c2,c3...*/
    static const std::vector<C> def = {c1,c2...};
    return def;
}

but then I cannot do B::defaultConf(). Maybe calling a static method creating a static B on which I call defaultConf() would work, but I'm looking for a more elegant way to do it.

I found Delegating copy constructor and const data initialization which talks about copy constructor so it is not really what i'm looking for but my question is the same : Is there a nice way to do it ?

Aucun commentaire:

Enregistrer un commentaire