Will c++1y allow in-class initialization of base class variables from a derived class?

StackOverflow https://stackoverflow.com/questions/22705743

  •  23-06-2023
  •  | 
  •  

문제

Instead of this:

class base
{
    protected:
        base( int value )
            : member{value}
        {}

        int member = 0;
};

class derived_1 : public base
{
    public:
        derived_1()
            : base{ 1 }
        {}
};

class derived_2 : public base
{
    public:
        derived_2()
            : base{ 2 }
        {}
};

This would be useful:

class base
{
    protected:
        int member = 0; // Default value
};

class derived_1 : public base
{
    base::member = 1; // Instead of passing it to a base class constructor
};

class derived_2 : public base
{
    base::member = 2;
};

Will c++1y support this, or similar, syntax?

도움이 되었습니까?

해결책

No, there are currently no plans to allow this. It seems a bit odd to allow an initializer to bypass a base class constructor (if any); it would seem to make more sense to allow a base-class specifier to contain an initializer:

class derived_1 : public base = {1}
{
};

You might consider submitting a proposal, if you can explain how the language would benefit (do you have a concrete use case?).

As a workaround, you might consider using a class template:

template<int I = 0>
class base { protected: int member = I; };

class derived_1: public base<1> {};

If you need to preserve a common base class, use an intermediate base class template:

class base { protected: int member = 0; };

template<int I>
class base_init: public base { base_init() { base::member = I; } };

class derived_1: public base_init<1> {};

Not sure if it's relevant, but the rules on aggregates and aggregate initialization look likely to change in C++14: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3653.html

다른 팁

No and Never.

All fields of base class must be initialized in the constructor in base class. Only the constructor in base class know how its field should be initialized.

You can and must initialize an object or its fields through its constructor.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top