Will C ++ 1y allow inside a class to initialize variables of a base class from a derived class?

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 helpful:

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?

+4
source share
2 answers

No, there are currently no plans to allow this. It seems a little strange that the initializer can bypass the constructor of the base class (if any); it would be wiser to let the base class specifier contain an initializer:

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

You can consider presenting a proposal if you can explain how the language will be useful (do you have a specific use case?).

As a workaround, you can use the class template:

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

class derived_1: public base<1> {};

, :

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> {};

, , ++ 14: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3653.html

+7

.

. , .

.

0

Source: https://habr.com/ru/post/1533856/


All Articles