-1

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;
}
mana
  • 545
  • 4
  • 12
  • 2
    You have *two different and distinct and unrelated* variables named `inner1_` – Some programmer dude Aug 17 '20 at 04:23
  • 1
    No, but then you use the *uninitialized* `int` variable, whose value is indeterminate and you will have *undefined behavior*. – Some programmer dude Aug 17 '20 at 04:27
  • 1
    By the way, the "nesting" is a red herring, it's unrelated to your problem. You would have the same problem if `Inner1` was defined in the global scope as well. – Some programmer dude Aug 17 '20 at 04:32
  • 1
    As for the "proper" solution, please do some research about *constructor initializer lists*. – Some programmer dude Aug 17 '20 at 04:33
  • 1
    This doesn't address the question, but be careful about the words "outer" and "inner" here. In some languages there is a perverse relationship between objects of an outer class and an inner class. In C++ there is no connection; the "inner" class is just a class whose definition is nested inside the "outer" class. Usually that's referred to as a **nested class**, not an inner class. – Pete Becker Aug 17 '20 at 13:50

1 Answers1

0

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);
kesarling He-Him
  • 1,944
  • 3
  • 14
  • 39