c++ - Pass in-class initialized const member to Base constructor? -


i have in-class initialized const member in derived class i'd pass constructor of base class.

example:

class base{ public:     base(int a) : i(a){} private:     int i; };  class derived : base{ public:     derived() : base(a){} private:     const int = 7; };  int main(){     derived d; } 

however spawns uninitialized error:

field 'a' uninitialized when used here [-wuninitialized] 

i under impression const initializing set value directly allowing passed derived ctor in manner. doing wrong or under wrong impression? when const in-class initialized members initialized?

your question,

when const in-class initialized members initialized?

is bit of red herring. "in-class initialized" doesn't mean anything; brace-or-equal initializer syntactic sugar , takes place of corresponding constructor initalizer list slot. const has no special bearing. real question should be:

when non-static data members initialized?

the details don't matter much, suffice non-static data members initialized after base subobjects initialized, proposed construction cannot work.

the straight-forward answer not use brace-or-equals-initializer , use normal (possibly defaulted) constructor parameter. here few examples:

struct foo : base {     const int a;      // default constructor, mention value once     foo(int _a = 10) : base(_a), a(_a) {}      // dryolent default constructor     foo() : base(10), a(10) {}      // delegating default constructor     foo() : foo(10) {}     private: foo(int _a) : base(_a), a(_a) {} }; 

alternatively, if value of constant doesn't need configurable, can make per-class constant (rather per-object):

struct foo : base {     static const int = 10;     foo() : base(a) {} };  const int foo::a;  // if odr-use foo::a 

Popular posts from this blog