c++ Child class Unable to initialize Base class's member variable?

十年热恋 提交于 2020-01-06 08:23:10

问题


So this question adds to my previous question about initializing member vector in an initialization list..

Here are my base & derived class definitions...

class Base {
public:
    std::vector<int> m_Vector;
}


class Derived : public Base {
    Derived() : m_Vector {1, 2, 3} {}      // ERROR when referring to m_Vector
}

When trying to initialize Derived's m_Vector.. I get an error in Visual Studio saying that

"m_Vector" is not a nonstatic data member or base class of class "Derived"

Why can't derived class refer to m_Vector in this case..?


回答1:


You can modify the data member in the derived class constructor after it has been initialized, but you need to perform the initialization in the base class. For example,

class Base 
{
public:
    std::vector<int> m_Vector;
    Base() : m_Vector {1, 2, 3} {} 
};

class Derived : public Base 
{

};

This is because the base class (and by extension, all its data members) are initialized before the derived class and any of its members.

If you need to be able to control the initialization values of Base's data members from Derived, you can add a suitable constructor to Base, and use this in Derived:

class Base 
{
public:
    std::vector<int> m_Vector;
    Base(const std::vector<int>& v) : m_Vector(v) {}
    Base(std::vector<int>&& v) : m_Vector(std::move(v)) {}
};

class Derived : public Base 
{
public:
  Derived() : Base({1, 2, 3}) {}

};


来源:https://stackoverflow.com/questions/24873762/c-child-class-unable-to-initialize-base-classs-member-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!