user2138149
user2138149

Reputation: 16625

C++14 Initializing inherited member in class constructor initialization list

I have a base class

class A
{
    protected:

    int a;
};

And a class which is derived:

class B : public A
{

    B(int a_val)
        : a{a_val} // not allowed by compiler?
    {
    }
};

I can solve the problem by:

    B(int a_val)
    {
        a = a_val;
    }

Is this "the solution", or can I do what I originally tried to do?

Of course, I could do this:

    B(int a_val)
        : A(a_val)
    {
    }

and change class A

    A(int a_val)
        : a{a_val}
    {
    }

However this isn't really "better" in the context of what I am doing.

In reply to an answer below (by swang): Can I therefore do this?

B(int a_val)
    : A(), a{a_val}
{
}

Upvotes: 0

Views: 120

Answers (1)

swang
swang

Reputation: 5249

When you do this:

class B : public A
{

    B(int a_val)
        : a{a_val} // not allowed by compiler?
    {
    }
};

You are trying to initialise a variable that doesn't belong to class B yet, so the right solution is

B(int a_val)
   : A(a_val)
{
};

You can do this

B(int a_val)
{
    a = a_val;
};

Because before a = a_val, the default construct of A has been called, and A::a has been default initialised.

Upvotes: 3

Related Questions