Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C++ Q: Illegal member initialization trying to set base class member in derived

EDITED: Removed the Base class being a template class, as this has no bearing on the issue as others have pointed out to me.

It has been a while since working with basic C++ concepts, and specifically the nuances of member initialization lists.
https://en.cppreference.com/w/cpp/language/constructor

class Base
{
public:
    Base() {}

protected:
    int m_Value;
};

class Derived: public Base
{
public:
    Derived() :
    Base(),
    m_Value(-1)
    {
        m_Value = -1;
    };
};

Why am I getting (in VS2019 using C++ v17) an error C2614 "illegal member initialization: ‘m_value’is not a base or member" for m_Value(-1) in the Derived constructor member initialization list, however explicitly setting it within the body of the Derived ctor is ok?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Thanks!
David

>Solution :

This has nothing to do with templates. A derived class cannot invoke the constructors of the base class’s members directly. You must use the base class’s constructor to initialize the base class’s members.

This is because the base class has already initialized its members by the time the derived class is initialized.


class Base
{
public:
    Base(int value) : m_Value(value) {}

protected:
    int m_Value;
};

class Derived: public Base
{
public:
    Derived() :
    Base(-1)
    {
    };
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading