1

I am trying to access the outer class variable cell[i][j] from the inner class method iterateForward.

I do not want to pass this of outer class to iterateForward as iterateForward(Matrix&) , since it will add a parameter to iterateForward.

Inner class Method:

Pos Matrix::DynamicCellIterator::iterateForward(){
                    ....................
         (Example)    outerRef.cell[i][j].isDynamic = true;          
                    .....................
                    }

Here is my class:

 class Matrix { 
       class DynamicCellIterator{
            Cell* currentCellPtr;
            Matrix& outerRef;  //This will be the key by which i'll get access of outer class variables
        public:
            DynamicCellIterator(Matrix&);
                Pos iterateForward();
        };
        Cell cell[9][9];
        DynamicCellIterator dynIte(*this); // I have a problem of initializing the outerRef variable.
        Error errmsg;
        bool  consistent;


    public:
        Matrix();
        Matrix(Matrix&);
            ................
    }


//Here I tried to initialize the outerRef.
    Matrix::DynamicCellIterator::DynamicCellIterator(Matrix& ref){
        this->currentCellPtr = NULL;
        this->outerRef = ref;
    }

How can I initialize outerRef?

Mat
  • 202,337
  • 40
  • 393
  • 406
Muthu Ganapathy Nathan
  • 3,199
  • 16
  • 47
  • 77
  • 1
    Not sure what error you're getting, but I'd write it Matrix::DynamicCellIterator::DynamicCellIterator(Matrix& ref):outerRef(ref){ – Joachim Isaksson Jan 28 '12 at 17:37
  • Possible duplicate of [Can inner classes access private variables?](http://stackoverflow.com/questions/486099/can-inner-classes-access-private-variables) – Jason C Oct 31 '16 at 23:18

2 Answers2

4

You need to initialize member references in the constructor's initialization list. And do the same for the dynIte member: initialize it in outer's constructor.

Something like this:

class Outer {
    class Inner {
        int stuff;
        Outer &outer;

        public:
            Inner(Outer &o): outer(o) {
                // Warning: outer is not fully constructed yet
                //          don't use it in here
                std::cout << "Inner: " << this << std::endl;
            };
    };

    int things;
    Inner inner;

    public:
        Outer(): inner(*this) {
                std::cout << "Outer: " << this << std::endl;
        }
};
Mat
  • 202,337
  • 40
  • 393
  • 406
3

Have the constructor of the inner class accept a pointer to an object of the outer class and store it in a data member for later use. (This is essentially what Java does automatically under the hood, btw.)

fredoverflow
  • 256,549
  • 94
  • 388
  • 662