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