Access to Members of Classes within Classes?

My question boils down to how do I access a member of a class within another class, that's a member of that class? For example, in the below classes, both Grid2D and Cell are a type of Rect2D. Cell is contained within (and a member of) Grid2D. I will eventually initialize Grid2D to accept a number of rows and columns, stored in private variables of similar name. HOW do I access these variables within Cell? The reason I want to access them is because Rect2D contains a point value location, and to determine the location of Cell 14, for example, I need to know the number of rows and columns in the grid.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include "Rect2D.h"

class Cell : public Rect2D {
public:

	friend class Grid2D;

	Cell& operator[] (int index) { 
		_index = index; 
		return *this;
	}

	int test() { return (_index * _rows); }

private:
	int _index;
};

class Grid2D : public Rect2D {

public:

	friend class Cell;
	Cell cell;

private:

	int _rows, _columns;

};


This is how I'd expect it to work in a main() method:

1
2
3
Grid2D g;
std::cout << g.cell[3].test() << std::endl; 
//If _rows = 2, then this should print 6 to the screen 
The only way to access private members is through friend.
http://www.cplusplus.com/doc/tutorial/inheritance/
Friend relationships won't work, I've tried. However, I was able to find a solution. Thanks for the help anyway, though. The answer seems to be with nested classes. The code below works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

#include <iostream>
#include <vector>
#include "Rect2D.h"


class Grid2D : public Rect2D {

public:

	Grid2D() : _rows(2), _columns(2), cell(*this) {};

	class Cell {
	public:
		Cell(Grid2D& g) : G(g) {};
		Cell& operator[] (int index) {
			_index = index;
			return *this;
		}

		int test();

	private:
		Grid2D& G;
		int _index;
	};

	Cell cell;

private:
	int _rows, _columns;
};

int Grid2D::Cell::test() { return (_index * G._rows); }
Topic archived. No new replies allowed.