Search code examples
c++datamember

Member of nested class isn't being initialized by the constructor


I have two classes, Outer and Inner. Outer contains no data members. Inner contains one data member, inner1_. When I call the constructor for outer, I create an instance of the class Inner, inner1. When the constructor for inner1 is called, its data member, inner1_, should be a vector of length n. However, after inner1 is constructed, I find that its data member has length 0. Why am I getting this unexpected behavior?

#include <iostream>
#include <vector>

class Outer {
public:
    Outer(int n) {
        Inner1 inner1{n};
        inner1.printsize();
    }
private:
    class Inner1 {
    public:
        Inner1(int n) {
            std::vector<double> inner1_(n);
        }
        void printsize() {
            std::cout << inner1_.size();
        }
        std::vector<double> inner1_;
    };

};
int main() {
    Outer test(7);
    return 0;
}

Solution

  • You have redeclared inner1_ in the ctor which is overshadowing the class variable. You probably want to resize the vector. This is how one resizes the vector:

    inner1_.resize(n);