c++ Child class Unable to initialize Base class

2019-08-26 23:56发布

问题:

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

};