C++ Classes: Loops in Constructor

  • Thread starter Thread starter TeTeC
  • Start date Start date
  • Tags Tags
    Loops
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
1 reply · 3K views
TeTeC
Messages
55
Reaction score
0
Hello!

I'm experimenting with classes in C++. It works fine for now, but there is something I can't find an explanation for. I tried to develop a 'matrix' class, and I overloaded some operators in order to define addition or multiplication for matrices. This works like a charm, except for the part where I make a default constructor to initialize my matrix.

In order to do this, I first thought about doing a double loop to initialize all the values in the matrix. In my class CMatrix, the fragment of code is:

Code:
	CMatrix () {	
		for (int i = 0; i < ROW; i++){
			for (int j = 0; i < COL; j++){
				matrix[i][j] = 0;
			}
		}
        };

Note: that's how I defined ROW and COL:

#define ROW 3
#define COL 3

However, it doesn't work. The compilation is fine, but at some point when the program is executed, Visual Express opens a windows where it is written:

'Violation of access at 0x00030ffc, etc.' (I can't translate everything, I have the french version of the software, but there is nothing else important to say.)

Since my matrices are 3x3, I tried to initialize all the values by 'brute force':

Code:
CMatrix () {	
	matrix[0][0] = 0;
	matrix[1][0] = 0;
	matrix[2][0] = 0;
	matrix[0][1] = 0;
	matrix[1][1] = 0;
	matrix[2][1] = 0;
	matrix[0][2] = 0;
	matrix[1][2] = 0;
	matrix[2][2] = 0;
};

And it works! I don't see any mistakes in my loops (and VE would have found them). So, is there something I am not allowed to do?

Thank you!
 
Last edited:
Physics news on Phys.org
Woops, that's the wrong sub-forum. Could somebody move this thread and delete this message ? Thanks.